Menu
CoddyTech

封装

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

Go 的封装通常遵循包边界:同一个包中的其他代码可以访问小写字段。Rust 的隐私规则遵循模块。公有类型可以在其定义模块中保留私有字段,并提供精简的公有 API。

下面的 Rust 模块公开了一个门,它唯一的状态转换是关闭。模块外部的代码可以调用公有操作,但不能直接重新打开私有字段。Go 示例是一个单包程序,因此小写字段对 main 可见;如果从单独的包中导出 Gate,调用方就无法访问该字段。

完整的 Go 对比程序:

package main
import "fmt"
type Gate struct { closed bool }
func NewGate() Gate { return Gate{} }
func (g *Gate) Close() { g.closed = true }
func (g Gate) IsClosed() bool { return g.closed }
func main() { g := NewGate(); g.Close(); fmt.Println(g.IsClosed()) }

Go 输出:

true

完整的 Rust 教学程序:

mod gate {
    pub struct Gate { closed: bool }
    impl Gate {
        pub fn new() -> Gate { Gate { closed: false } }
        pub fn close(&mut self) { self.closed = true; }
        pub fn is_closed(&self) -> bool { self.closed }
    }
}
fn main() {
    let mut g = gate::Gate::new();
    g.close();
    println!("{}", g.is_closed());
}

Rust 输出:

true
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 会拒绝负数金额或大于余额的金额。每次被拒绝的操作都不会改变状态;零是可接受的。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自我测试

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

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

自己练习: Rust 在线编译器