封装
Coddy 面向 C 开发者的 Rust 课程的第 33 课,共 48 课。
Rust 通过模块边界强制执行隐私规则。公共结构体可以将字段设为私有,只公开能够维护其规则的操作。在 C 中,头文件可以通过不完整类型隐藏结构体定义,而实现函数可以访问完整记录。Rust 通过模块和 pub 直接表达这种边界。这段代码公开了标签比较操作,但不会让调用代码直接访问存储的字符串。对于可能失败的操作,应先进行验证,并且只有在所有检查都成功后才修改数据。
C
#include <stdio.h>
#include <string.h>
struct Tag;
int tag_matches(const struct Tag *tag, const char *text);
struct Tag { const char *text; };
int tag_matches(const struct Tag *tag, const char *text) { return strcmp(tag->text, text) == 0; }
int main(void) {
struct Tag tag = {"blue"};
printf("%d %d\n", tag_matches(&tag, "blue"), tag_matches(&tag, "Blue"));
return 0;
}Rust
mod tag {
pub struct Tag { text: String }
impl Tag {
pub fn new(text: &str) -> Tag { Tag { text: text.to_string() } }
pub fn matches(&self, text: &str) -> bool { self.text == text }
}
}
fn main() {
let t = tag::Tag::new("blue");
println!("{} {}", t.matches("blue"), t.matches("Blue"));
}在结构体上添加 pub 并不会公开私有字段。在其他模块中调用它的公共方法。
挑战
简单实现 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));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Rust中的所有课
自己练习: Rust 在线编译器