特征与契约
Coddy 面向 C 开发者的 Rust 课程的第 36 课,共 48 课。
trait 用来声明不同类型承诺提供的行为。使用 impl Trait for Type 来实现所需的方法。trait 还可以提供调用所需方法的默认方法,这样每个实现都会继承基于自身结果构建的行为。要在某个值上使用 trait 的方法,先将该 trait 引入作用域。C 可以用上下文指针和函数指针来表示类似的可调用行为,但这些签名和类型转换需要手动维护。Rust 会检查每个实现是否满足声明的方法类型。
C
#include <stdio.h>
struct Named { const void *context; const char *(*name)(const void *); };
struct Person { const char *name; };
const char *person_name(const void *context) { return ((const struct Person *)context)->name; }
void greet(struct Named item) { printf("Hi %s\n", item.name(item.context)); }
int main(void) {
struct Person p = {"Ada"};
struct Named n = {&p, person_name};
greet(n);
return 0;
}Rust
trait Named {
fn name(&self) -> &str;
fn greeting(&self) -> String { format!("Hi {}", self.name()) }
}
struct Person { name: String }
impl Named for Person { fn name(&self) -> &str { &self.name } }
fn main() {
let p = Person { name: "Ada".to_string() };
println!("{}", p.greeting());
}trait 不是基类结构体,也不会存储继承来的字段。每种实现了 trait 的类型都拥有自己的数据。
挑战
简单定义 charge::Charge,其中必须实现 cost(&self, units: i32) -> i32,并提供默认方法 pair(&self, first: i32, second: i32) -> i32。该方法会分别对每个参数调用 cost,并将结果相加。在不同模块中,为 flat::Flat { pub fee: i32 } 和 per_unit::PerUnit { pub rate: i32 } 实现该 trait。固定费用在单位数为 0 时为 0,否则为该费用;按单位计费时,费用为费率乘以单位数。单位数、费用和费率均为非负数。solve 读取 mode amount first second,其中 mode 为 flat 或 unit,三个整数均不超过 1000。返回第一项费用、第二项费用和两项合计费用,各项之间用空格分隔。
实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在打印返回的文本后添加一个换行符。
你的代码应写在 exercise.rs、charge.rs、flat.rs 和 per_unit.rs 中。main.rs 中包含提供的输入/输出代码,不能编辑。
亲手试试
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod charge;
mod flat;
mod per_unit;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 开始公开 API 检查
use charge::Charge;
let f = flat::Flat { fee: 19 }; let u = per_unit::PerUnit { rate: 7 };
assert_eq!(f.cost(0), 0); assert_eq!(f.cost(11), 19); assert_eq!(f.pair(0, 8), 19);
assert_eq!(u.cost(6), 42); assert_eq!(u.cost(0), 0); assert_eq!(u.pair(3, 8), 77);
struct CustomCharge;
impl charge::Charge for CustomCharge { fn cost(&self, units: i32) -> i32 { units * units + 2 } }
let custom = CustomCharge;
assert_eq!(custom.pair(3, 5), 38); assert_eq!(custom.pair(0, 0), 4);
assert_eq!(f.pair(2, 3), 38);
// 结束公开 API 检查
println!("{}", exercise::solve(&input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Rust中的所有课
自己练习: Rust 在线编译器