Menu
CoddyTech

trait 与契约

Coddy 面向 C# 开发者的 Rust 课程的第 36 课,共 48 课。

C# 接口描述了某种类型提供的操作。Rust trait 也定义了一份契约,但实现写在单独的 impl Trait for Type 块中,而不是基类型列表中。trait 可以包含必需方法和默认方法。默认方法使用 trait 的契约,而不是继承的实例字段。示例定义了一份生成声音的契约和一个铃铛实现。Rust trait 位于作用域内,因此方法调用语法可以解析其方法。一个类型可以实现多个 trait,这不会形成类继承树。Rust 通过一致性规则限制实现的编写位置,因此不允许为外部类型任意实现相冲突的外部 trait。在普通的领域建模中,组合加上 trait 契约可以提供共享行为,无需基类。这个简单的声音方法展示了实现语法,同时没有实现练习中的定价规则和默认聚合行为。

完整的 C# 程序:

using System;
interface ISound { string Sound(); }
class Bell : ISound { public string Sound() { return "ding"; } }
class Program {
    static void Main() { Console.WriteLine(new Bell().Sound()); }
}

完整的 Rust 程序:

trait Sound { fn sound(&self) -> &'static str; }
struct Bell;
impl Sound for Bell {
    fn sound(&self) -> &'static str { "ding" }
}
fn main() { println!("{}", Bell.sound()); }
challenge icon

挑战

简单

定义 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;否则为 fee。按单位计费时,费用为 rate 乘以单位数。所有单位数、费用和费率均为非负数。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));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 Rust中的所有课

自己练习: Rust 在线编译器