Menu
CoddyTech

trait 与契约

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

Python 的鸭子类型允许在对象于运行时提供所需行为时执行某项操作。Rust trait 用于命名行为契约,并在编译时检查实现。trait 可以声明必需的方法,也可以基于这些方法提供默认实现。结构体必须显式实现 trait;仅仅定义一个同名方法并不能满足 trait 约束。trait 描述行为,不要求共享数据布局或通过类继承实现。本例通过 trait 为一盏灯提供标签。这样,代码就可以依赖命名操作,而不必依赖具体实现所使用的字段。

Python:完整程序

class Lamp:
    def label(self):
        return "desk"
def show(item):
    print(item.label())
show(Lamp())

Rust:完整程序

trait Label { fn label(&self) -> &'static str; }
struct Lamp;
impl Label for Lamp { fn label(&self) -> &'static str { "desk" } }
fn show<T: Label>(item: &T) { println!("{}", item.label()); }
fn main() { show(&Lamp); }

Rust trait 并不是一种开放式承诺,不会自动接受任何拥有同名方法的类 Python 对象。

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 } 实现该特征。固定费用在单位数为零时为零,否则为该费用;按单位计费的费用为费率乘以单位数。所有单位数、费用和费率都为非负数。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自我测试

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

面向 Python 开发者的 Rust中的所有课

自己练习: Rust 在线编译器