特征与契约
Coddy 面向 JavaScript 开发者的 Rust 课程的第 36 课,共 48 课。
JavaScript 没有接口声明。调用方与对象之间的约定采用鸭子类型:如果调用运行时对象有一个 label 方法,调用就能成功;如果没有,程序会在那一行抛出 TypeError。Rust 的 trait 用来命名行为,而类型会通过 impl Trait for Type 块显式实现它,编译器会在程序运行前检查这一点。仅仅定义一个同名方法并不能实现该 trait。这些示例会返回一个状态标签:JavaScript 对象只需有这个方法,而 Rust 的 Link 会显式选择实现 Status。trait 可以提供基于必需方法构建的默认方法,但它不存储实例字段,也不形成类层次结构,因此不同实现可以采用完全不同的表示方式。在另一个模块中调用 trait 的方法前,需要用 use 将该 trait 引入作用域。你可以把 trait 看作调用方可以要求的一种能力。调用使用静态分发还是动态分发,取决于调用方如何接收该实现,后续课程会对此进行区分。
完整的独立 JavaScript 程序:
// 不需要接口:任何有 label 方法的对象都可以。
const link = { label() { return "online"; } };
console.log(link.label());
JavaScript 输出:
online
完整的独立 Rust 程序:
trait Status { fn label(&self) -> &'static str; }
struct Link;
impl Status for Link { fn label(&self) -> &'static str { "online" } }
fn main() { let link = Link; println!("{}", link.label()); }
Rust 输出:
online
挑战
简单定义 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 }。固定费用在单位数为 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 JavaScript 开发者的 Rust中的所有课
自己练习: Rust 在线编译器