Menu
CoddyTech

特征与契约

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

Java 接口声明由类实现的行为。Rust trait 声明由类型通过 impl Trait for Type 实现的行为。实现与结构体定义是分开的。Trait 可以提供默认方法和关联项,但它们不是带有继承实例字段的 Java 基类。一个类型可以实现多个 trait。

使用 &self 的 trait 方法只需要对接收者进行共享访问。当 trait 位于作用域内时,代码就可以调用它。之后,约束可以让函数接受任何实现了该 trait 的类型。Rust 还通过一致性规则限制 crate 可以添加哪些 trait 实现;它并不能随意为任何外部类型打补丁。这个示例返回一个静态声音标签,用来展示一种约定,不涉及算术或定价模型。

Java:完整程序

class Main {
    interface Audible { String sound(); }
    static class Bell implements Audible {
        public String sound() { return "ding"; }
    }
    public static void main(String[] args) {
        Bell bell = new Bell();
        System.out.println(bell.sound());
    }
}

Rust:完整程序

trait Audible { fn sound(&self) -> &'static str; }
struct Bell;
impl Audible for Bell { fn sound(&self) -> &'static str { "ding" } }
fn main() {
    let bell = Bell;
    println!("{}", bell.sound());
}

注意:实现 trait 并不会将值放入超类对象中,也不要求使用动态分发。

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,否则为费用值;按单位收费则为费率乘以单位数。单位数、费用和费率都不会是负数。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自我测试

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

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

自己练习: Rust 在线编译器