Menu
CoddyTech

封装

Coddy 面向 Kotlin 开发者的 Rust 课程的第 33 课,共 48 课。

Kotlin 的 private 成员受类级别的访问边界限制,而顶层 private 声明只能在文件内访问。Rust 的可见性则遵循模块树。公共结构体可以隐藏字段,不让父模块访问,同时公开构造和操作。仅有 impl 块并不会创建 Kotlin 风格的私有类边界。

两个程序都公开了门的操作和状态查询,同时隐藏了调用方直接更改所存标志的方式。定义该结构体的 Rust 模块中的其他代码仍可访问私有字段,因此在保护不变量时要选择合适的模块边界。公共结构体不会自动公开所有字段。你可以在稳定的 API 背后更改表示方式,但仅有封装还不够:每个公开操作都必须维护所承诺的状态规则,并在需要时验证输入。

Kotlin:完整程序

class Door {
    private var locked = false
    fun lock() { locked = true }
    fun isLocked() = locked
}
fun main() {
    val door = Door()
    door.lock()
    println(door.isLocked())
}

Rust:完整程序

mod door {
    pub struct Door { locked: bool }
    impl Door {
        pub fn new() -> Self { Self { locked: false } }
        pub fn lock(&mut self) { self.locked = true; }
        pub fn is_locked(&self) -> bool { self.locked }
    }
}
fn main() {
    let mut door = door::Door::new();
    door.lock();
    println!("{}", door.is_locked());
}

Rust 字段的隐私性由定义它的模块决定,而不只由某个 impl 块决定。

challenge icon

挑战

简单

实现带有私有余额的 wallet::Wallet。Wallet::new(balance: i32) -> Option<Wallet> 会拒绝负余额。balance(&self) -> i32 用于读取余额。deposit(&mut self, amount: i32) -> bool 会拒绝负数金额,否则将金额加到账户中。withdraw(&mut self, amount: i32) -> bool 会拒绝负数金额或超过余额的金额。每次被拒绝的操作都不会改变状态;金额为 0 时操作也会被接受。solve 会读取一个非负初始余额,后面跟着由命令和金额组成的配对项:d amount 或 w amount。每行返回一个结果,格式为 true:balance 或 false:balance,最后一行是 balance:n。所有值和中间余额都在 i32 的范围内。

实现所需的导出 API,并从 exercise::solve(input: &str) -> String 返回结果,末尾不要添加换行符。不要在可编辑代码中打印内容。锁定的驱动程序会独立检查所需的 API,读取全部标准输入,并在打印返回的文本时添加一个末尾换行符。

你的代码写在 exercise.rs 和 wallet.rs 中。main.rs 包含提供的输入和输出代码,不能编辑。

亲手试试

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod wallet;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 开始公开 API 测试
assert!(wallet::Wallet::new(-17).is_none());
let mut a = wallet::Wallet::new(43).unwrap(); let b = wallet::Wallet::new(6).unwrap();
assert!(!a.withdraw(44)); assert_eq!(a.balance(), 43);
assert!(!a.withdraw(-2)); assert!(!a.deposit(-8)); assert_eq!(a.balance(), 43);
assert!(a.withdraw(43)); assert!(a.withdraw(0)); assert_eq!(a.balance(), 0);
assert!(a.deposit(11)); assert!(a.deposit(0)); assert_eq!(a.balance(), 11);
assert_eq!(b.balance(), 6); assert!(a.withdraw(4)); assert_eq!(a.balance(), 7);
    // 结束公开 API 测试
    println!("{}", exercise::solve(&input));
}
quiz icon自我测试

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

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

自己练习: Rust 在线编译器