特征对象
Coddy 面向 Java 开发者的 Rust 课程的第 38 课,共 48 课。
Java 中,接口类型的变量通常会引用在运行时选定的实现。Rust 提供了 &dyn Voice 这样的 trait 对象,用于在具体实现类型被隐藏在引用后面时进行动态分派。该引用提供对值的访问权限,以及通过 trait 进行分派所需的信息。Box<dyn Voice> 可以通过分配内存来拥有一个动态大小的 trait 值,但使用 trait 对象并不一定需要 Box。
相比之下,fn speak<T: Voice>(x: &T) 使用泛型类型参数,通常会在编译时针对其具体实例进行特化。trait 必须满足动态兼容性规则,才能用作 trait 对象;例如,任意泛型方法不能不受限制地通过这种方式进行分派。对 trait 对象的共享引用也有借用生命周期。它不会像 Java 引用那样,让短生命周期的所有者继续存活。
Java:完整程序
class Main {
interface Voice { String call(); }
static class Owl implements Voice { public String call() { return "hoot"; } }
public static void main(String[] args) {
Voice voice = new Owl();
System.out.println(voice.call());
}
}Rust:完整程序
trait Voice { fn call(&self) -> &'static str; }
struct Owl;
impl Voice for Owl { fn call(&self) -> &'static str { "hoot" } }
fn main() {
let owl = Owl;
let voice: &dyn Voice = &owl;
println!("{}", voice.call());
}易错点:dyn Trait 和泛型 T: Trait 是不同的分派和表示方式选择,并不是继承的不同写法。
挑战
简单定义 adjuster::Adjuster,其中包含 apply(&self, value: i32) -> i32。为 offset::Offset { pub amount: i32 } 实现该特征,它会加上自身的 amount;为 ceiling::Ceiling { pub maximum: i32 } 实现该特征,它会返回 value 和 maximum 中较小的值。pipeline::run(value: i32, steps: &[Box<dyn Adjuster>]) -> i32 按切片顺序对提供的每个对象应用一次操作,并将每次的结果传给下一个对象。空管道会返回输入值。solve 会读取一个初始整数,后面跟着完整的 add amount 或 cap maximum 键值对。创建拥有所有权的特征对象,并返回最终值。所有输入和中间结果都在 i32 范围内。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,不要在末尾添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并将返回的文本打印出来,末尾带一个换行符。
你的代码应放在 exercise.rs、adjuster.rs、offset.rs、ceiling.rs、pipeline.rs 中。main.rs 包含提供的输入/输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod adjuster;
mod offset;
mod ceiling;
mod pipeline;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 测试
use adjuster::Adjuster;
assert_eq!(offset::Offset { amount: -7 }.apply(19), 12);
assert_eq!(ceiling::Ceiling { maximum: 14 }.apply(22), 14);
assert_eq!(ceiling::Ceiling { maximum: 14 }.apply(-3), -3);
struct Times(i32);
impl adjuster::Adjuster for Times { fn apply(&self, v: i32) -> i32 { v * self.0 } }
let steps: Vec<Box<dyn adjuster::Adjuster>> = vec![Box::new(offset::Offset { amount: 4 }), Box::new(Times(3)), Box::new(ceiling::Ceiling { maximum: 32 })];
assert_eq!(pipeline::run(5, &steps), 27); assert_eq!(pipeline::run(8, &steps), 32);
assert_eq!(pipeline::run(5, &steps), 27);
assert_eq!(pipeline::run(-91, &[]), -91);
// 结束公开 API 测试
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Java 开发者的 Rust中的所有课
自己练习: Rust 在线编译器