Trait 对象
Coddy 面向 Ruby 开发者的 Rust 课程的第 38 课,共 48 课。
Ruby 数组可以存放不同类的对象,并为每个接收者分别分派 label。Rust 的 Vec 只有一种元素类型,因此目标代码存储拥有所有权的 Box<dyn Label> 指针,以提供通用的 trait 对象接口。Box 提供所有权和间接访问;dyn 描述用于动态分派的 trait 对象。泛型 T: Label 则会为每次实例化选择一种具体类型,而且不必使用动态分派。并非每个 trait 都能用作 trait 对象,因为其方法形式必须支持该接口。只有在运行时需要处理异构类型时才选择动态分派,不要以为每次方法调用或 trait 约束都需要装箱对象。
Ruby:完整程序
class Sun
def label; "day"; end
end
class Moon
def label; "night"; end
end
[Sun.new, Moon.new].each { |item| puts item.label }
Rust:完整程序
trait Label { fn label(&self) -> &'static str; }
struct Sun;
struct Moon;
impl Label for Sun { fn label(&self) -> &'static str { "day" } }
impl Label for Moon { fn label(&self) -> &'static str { "night" } }
fn main() {
let items: Vec<Box<dyn Label>> = vec![Box::new(Sun), Box::new(Moon)];
for item in &items { println!("{}", item.label()); }
}拥有所有权的间接访问和运行时的方法选择,是 Box<dyn Label> 中相互独立的两个部分。
挑战
简单定义 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 Rust中的所有课
自己练习: Rust 在线编译器