特征对象
Coddy 面向 C++ 开发者的 Rust 课程的第 38 课,共 48 课。
C++ 通常通过基类引用或拥有对象的智能指针访问派生对象;通过基类所有者删除对象时,需要合适的虚析构函数。Rust 的 dyn Trait 也支持运行时分派,它会将对值的访问与其实现的元数据配对。trait 对象的大小是动态的,因此要通过引用或拥有对象的指针(例如 Box)使用它。由装箱对象组成的向量可以拥有不同的具体实现类型。泛型代码则会在每次实例化时选择一种具体类型,通常采用静态分派。并非所有 trait 都支持 trait 对象:需要不受限制的泛型分派或直接返回 Self 的方法可能会导致无法使用 trait 对象。Rust 编译器会管理 trait 对象的销毁。传感器示例会读取彼此独立的对象并汇总观测值;此任务则应用一个顺序转换流水线。
完整的独立 C++17 程序:
#include <iostream>
#include <memory>
#include <vector>
struct Sensor { virtual ~Sensor() = default; virtual int read() const = 0; };
struct Fixed : Sensor { int read() const override { return 4; } };
struct Difference : Sensor { int read() const override { return 9 - 2; } };
int main() {
std::vector<std::unique_ptr<Sensor>> sensors;
sensors.push_back(std::make_unique<Fixed>());
sensors.push_back(std::make_unique<Difference>());
int total = 0;
for (const auto& sensor : sensors) total += sensor->read();
std::cout << total << '\n';
}完整的独立 Rust 程序:
trait Sensor { fn read(&self) -> i32; }
struct Fixed(i32);
struct Difference(i32, i32);
impl Sensor for Fixed { fn read(&self) -> i32 { self.0 } }
impl Sensor for Difference { fn read(&self) -> i32 { self.0 - self.1 } }
fn main() {
let sensors: Vec<Box<dyn Sensor>> = vec![Box::new(Fixed(7)), Box::new(Difference(9, 4))];
let sum: i32 = sensors.iter().map(|s| s.read()).sum();
println!("{}", sum);
}挑战
简单定义 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 配对项。创建拥有所有权的 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 Rust中的所有课
自己练习: Rust 在线编译器