trait 对象
Coddy 面向 C# 开发者的 Rust 课程的第 38 课,共 48 课。
C# 接口引用可以指向不同的实现类。Rust 的 &dyn Trait 同样会通过借用的 trait 对象隐藏具体的实现类型,并使用动态分派。Box<dyn Trait> 还会拥有该对象;动态分派和所有权选择是彼此独立的。带有 trait 约束的泛型函数通常会为每次实例化保留一个具体类型。用作 trait 对象的 trait 必须满足 dyn 兼容性规则:并非所有泛型 API 或返回自身类型的 trait API 都能通过 trait 对象调用。示例中有两个不同的标签提供者,并通过一个共同的接口访问它们。Rust 中的借用对象仍然有效,因为它们的具体所有者的生命周期长于视图数组。对于这些特定的视图,不需要堆分配。选择动态分派不会增加字段继承,选择泛型也不意味着值必须自动复制。
完整的 C# 程序:
using System;
interface ILabel { string Text(); }
class Local : ILabel { public string Text() { return "local"; } }
class Remote : ILabel { public string Text() { return "remote"; } }
class Program {
static void Main() {
ILabel[] labels = { new Local(), new Remote() };
foreach (var label in labels) Console.WriteLine(label.Text());
}
}完整的 Rust 程序:
trait Label { fn text(&self) -> &'static str; }
struct Local;
struct Remote;
impl Label for Local { fn text(&self) -> &'static str { "local" } }
impl Label for Remote { fn text(&self) -> &'static str { "remote" } }
fn main() {
let local = Local;
let remote = Remote;
let labels: [&dyn Label; 2] = [&local, &remote];
for label in &labels { println!("{}", label.text()); }
}挑战
简单定义 adjuster::Adjuster,其中包含 apply(&self, value: i32) -> i32。为 offset::Offset { pub amount: i32 } 实现该特征,使其将自身的 amount 加到值上;为 ceiling::Ceiling { pub maximum: i32 } 实现该特征,使其返回值和 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 Rust中的所有课
自己练习: Rust 在线编译器