Menu
CoddyTech

Trait 对象

Coddy 面向 Swift 开发者的 Rust 课程的第 38 课,共 48 课。

Swift 的存在类型 any Label 值可以通过同一个协议接口容纳不同的具体类型。Rust trait 对象通过选定的指针表示提供运行时分派,而 Box<dyn Label> 会增加拥有所有权的间接层。Box 拥有这块分配的内存;单独的 dyn 不拥有任何内容。泛型 T: Label 则针对每次实例化使用一个具体类型,本身并不需要动态分派。即使接口看起来相似,Swift 的存在类型存储方式和 Rust 的 Box 布局也并不相同。trait 对象兼容性会限制哪些 Rust trait 方法形式可以这样使用。只有在设计确实需要运行时异构性时才选择它,而不是把每个 trait 实现都装进 Box。

完整的独立 Swift 程序:

protocol Label { func label() -> String }
struct Sun: Label { func label() -> String { "day" } }
struct Moon: Label { func label() -> String { "night" } }
let items: [any Label] = [Sun(), Moon()]
for item in items { print(item.label()) }

Swift 输出:

day
night

完整的独立 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()); }
}

Rust 输出:

day
night
challenge icon

挑战

简单

定义 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 数值对。创建拥有所有权的 trait 对象,并返回最终值。所有输入和中间结果都在 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));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Swift 开发者的 Rust中的所有课

自己练习: Rust 在线编译器