封装
Coddy 面向 R 开发者的 Rust 课程的第 33 课,共 48 课。
R 闭包会保留词法环境,因此工厂函数可以提供操作,而无需将捕获的数据放入返回的列表中。闭包稍后使用所提供的 secret 值之前,force 会先确定该值;否则,惰性参数求值需要谨慎处理。这种组织方式并不能防范反射检查。Rust 通过模块强制实施字段隐私,公开 Token 方法,同时对父级隐藏其字段。这两个示例都通过 API 测试匹配和不匹配的候选值。定义 Rust 模块中的其他代码仍可访问私有字段,因此要谨慎设置不变量边界。隐藏状态仍需要通过操作来验证更改,并维护承诺的契约。
R:完整程序
new_token <- function(secret) {
force(secret)
list(matches = function(candidate) identical(secret, candidate))
}
token <- new_token("mint")
cat(tolower(as.character(token$matches("mint"))), "\n", sep = "")
cat(tolower(as.character(token$matches("sage"))), "\n", sep = "")
Rust:完整程序
mod access {
pub struct Token { secret: String }
impl Token {
pub fn fixed() -> Self { Token { secret: String::from("mint") } }
pub fn matches(&self, candidate: &str) -> bool { self.secret == candidate }
}
}
fn main() {
let token = access::Token::fixed();
println!("{}", token.matches("mint"));
println!("{}", token.matches("sage"));
}闭包的组织方式和 Rust 模块隐私使用不同的强制机制,即使两者都只公开有限的 API。
挑战
简单实现 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 Rust中的所有课
自己练习: Rust 在线编译器