Trait 对象
Coddy 面向 Kotlin 开发者的 Rust 课程的第 38 课,共 48 课。
Kotlin 接口引用支持调用在运行时选择的实现。Rust trait 对象(例如 &dyn Voice)也使用动态分派,并通过借用引用隐藏具体类型。指针包含对值的访问权限,以及选择其 trait 实现所需的信息。
Box<dyn Voice> 可以通过一次分配来拥有动态大小的实现,但 dyn 本身并不要求使用 Box。泛型 T: Voice 则会为每次实例化选择一个具体类型,通常支持静态分派。只有与 dyn 兼容的 trait 才能构成 trait 对象;任意泛型方法并不能自动通过 trait 对象调用。借用的 Rust voice 有生命周期限制,不能单靠自身让短生命周期的所有者继续存活。选择接口形式时,要将分派、表示方式和所有权分开考虑。
Kotlin:完整程序
interface Voice { fun call(): String }
class Owl : Voice { override fun call() = "hoot" }
fun main() {
val voice: Voice = Owl()
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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 Rust中的所有课
自己练习: Rust 在线编译器