学完正文后的补充练习
本页保存原笔记中超出当章前置知识的扩展内容。 先按顺序读完第 1–21 章,再阅读本页。 以下内容不作为前面章节的必做练习。
补充 1:结构体的内存布局(顺带一提)
来源:05 章。请在读完相关正文后再练习;本节组合多个章节的内容。
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
println!("Point 占 {} 字节", std::mem::size_of::<Point>()); // 8(两个 i32)
println!("i32 占 {} 字节", std::mem::size_of::<i32>()); // 4
}
字段是连续存放的(可能会有对齐填充)。所以结构体整体是一个连续的内存块, 这说明字段的存储方式,但不能据此断言结构体一定比几个局部变量更快;性能还取决于访问方式和编译器优化。
补充 2:补充示例
来源:06 章。请在读完相关正文后再练习;本节组合多个章节的内容。
while let 是“一直取,直到取不到“的惯用写法:
fn main() {
let mut stack = vec![1, 2, 3];
// pop() 返回 Option:还有元素就是 Some,空了就是 None
while let Some(top) = stack.pop() {
println!("弹出 {top}");
}
println!("栈空了");
}
输出依次为 弹出 3、弹出 2、弹出 1、栈空了,各占一行。
补充 3:match 守卫:相同变体还可以继续判断
来源:06 章。请在读完相关正文后再练习;本节组合多个章节的内容。
模式 if 条件 => 结果 中的 if 条件 叫匹配守卫。先匹配模式,再检查条件;
条件为 false 时继续尝试后面的分支。
fn describe(found: Option<u32>) -> &'static str {
match found {
Some(n) if n < 10 => "有值,但不足 10",
Some(_) => "有值,至少 10",
None => "没有值",
}
}
fn main() {
assert_eq!(describe(Some(3)), "有值,但不足 10");
assert_eq!(describe(Some(12)), "有值,至少 10");
assert_eq!(describe(None), "没有值");
}
可以写多个 Some 分支,但要保证后面的分支仍有机会匹配。
若第一个分支已经是没有守卫的 Some(n),它就接住了所有 Some,后面的 Some 分支不可达。
补充 4:综合例子:库存管理
来源:06 章。请在读完相关正文后再练习;本节组合多个章节的内容。
这个例子组合使用 struct 和 enum,并使用第 8 章的 Vec<Item>:
它是可增长的商品列表,Vec::new() 创建空列表,.push(...) 添加商品。
for item in &mut self.items 依次借用列表中的商品,借用规则与 ch04 一样。
#[derive(Debug, Clone)]
struct Item {
name: String,
quantity: u32,
}
#[derive(Debug)]
enum StockResult {
Added { name: String, amount: u32 },
Removed { name: String, amount: u32 },
NotFound { name: String },
NotEnough { name: String, have: u32, want: u32 },
}
struct Inventory {
items: Vec<Item>,
}
impl Inventory {
fn new() -> Inventory {
Inventory { items: Vec::new() }
}
/// 按名字找商品,找到了返回可变引用(这样才能直接改)
fn find_mut(&mut self, name: &str) -> Option<&mut Item> {
for item in &mut self.items {
if item.name == name {
return Some(item);
}
}
None
}
fn add(&mut self, name: &str, amount: u32) -> StockResult {
match self.find_mut(name) {
Some(item) => {
item.quantity += amount; // 直接改
StockResult::Added { name: name.to_string(), amount }
}
None => {
self.items.push(Item { name: name.to_string(), quantity: amount });
StockResult::Added { name: name.to_string(), amount }
}
}
}
fn remove(&mut self, name: &str, amount: u32) -> StockResult {
match self.find_mut(name) {
None => StockResult::NotFound { name: name.to_string() },
// match 里的"守卫":先匹配形状,再判断条件
Some(item) if item.quantity < amount => StockResult::NotEnough {
name: name.to_string(),
have: item.quantity,
want: amount,
},
Some(item) => {
item.quantity -= amount;
StockResult::Removed { name: name.to_string(), amount }
}
}
}
fn total_quantity(&self) -> u32 {
let mut total = 0;
for item in &self.items {
total += item.quantity;
}
total
}
}
fn main() {
let mut inv = Inventory::new();
println!("{:?}", inv.add("苹果", 10));
println!("{:?}", inv.add("苹果", 5));
println!("{:?}", inv.remove("苹果", 3));
println!("{:?}", inv.remove("香蕉", 1));
println!("{:?}", inv.remove("苹果", 100));
println!("总库存 {}", inv.total_quantity());
}
输出:
Added { name: "苹果", amount: 10 }
Added { name: "苹果", amount: 5 }
Removed { name: "苹果", amount: 3 }
NotFound { name: "香蕉" }
NotEnough { name: "苹果", have: 12, want: 100 }
总库存 12
三个值得注意的点:
find_mut返回Option<&mut Item>—— 借一个可变引用出来, 调用方拿到就能直接改,不需要“复制出来改完再塞回去“。这是 ch04 借用规则的实战用法。Some(item) if item.quantity < amount—— match 的守卫(guard), 先匹配形状再判条件。它让“找得到但不够“这种情况有了专门的分支。- 返回值用 enum 而不是 bool ——
StockResult把“失败原因“也带回来了, 调用方可以据此显示不同提示。如果返回 bool,调用方只能干瞪眼。
补充 5:多文件项目的分层示意
来源:07 章。请在读完相关正文后再练习;本节组合多个章节的内容。
下面是项目结构示意;随后展示的片段省略了 Config::from_args 等实现,
不能直接拼起来运行。要练习完整的多文件项目,可以先运行第 7 章的多文件加法示例。
myapp/
├── Cargo.toml
└── src/
├── main.rs # 只负责:解析命令行、调 lib、打印结果、退出码
├── lib.rs # 把所有模块串起来,定义公开 API
├── config.rs # 配置解析
├── models.rs # 数据结构(struct / enum)
├── services.rs # 声明 fetch、store 子模块
└── services/
├── fetch.rs
└── store.rs
main.rs 应该很薄 —— 它只做“把东西接起来“,真正的逻辑放在 lib.rs 和各模块里。
为什么要有 lib.rs:它提供可供其他 crate 导入的 API。
库和二进制都可以写单元测试;集成测试能直接导入库的公开 API,不能直接导入二进制里的函数。
// src/main.rs —— 薄
use myapp::{Config, run};
fn main() {
let config = Config::from_args();
if let Err(e) = run(config) {
eprintln!("错误:{e}");
std::process::exit(1);
}
}
// src/lib.rs —— 厚
mod config;
mod models;
mod services;
pub use config::Config; // 重新导出,让用户能用 myapp::Config
pub fn run(config: Config) -> Result<(), Box<dyn std::error::Error>> {
// 真正的逻辑
Ok(())
}
pub use 叫重新导出:把内部模块的东西提到顶层,用户不用知道你的内部结构。
补充 6:排序输出
来源:08 章。请在读完相关正文后再练习;本节组合多个章节的内容。
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for word in "b a b c a b".split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
// HashMap 无序,要按次数排序得先转成 Vec
let mut pairs: Vec<(&str, i32)> = counts.into_iter().collect();
// 次数降序,次数相同按字母升序
pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
for (word, n) in pairs {
println!("{n:>3} {word}");
}
}
输出:
3 b
2 a
1 c
补充 7:综合练习:完整的词频统计
来源:08 章。请在读完相关正文后再练习;本节组合多个章节的内容。
use std::collections::HashMap;
fn word_frequency(text: &str) -> HashMap<String, usize> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
// 去掉首尾的非字母数字字符(标点)
let cleaned = word
.trim_matches(|c: char| !c.is_alphanumeric())
.to_lowercase();
if cleaned.is_empty() {
continue;
}
*counts.entry(cleaned).or_insert(0) += 1;
}
counts
}
fn main() {
let text = "The quick brown fox jumps over the lazy dog. The dog sleeps.";
let counts = word_frequency(text);
let mut sorted: Vec<(&String, &usize)> = counts.iter().collect();
sorted.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
for (word, count) in sorted {
println!("{count:>3} {word}");
}
}
输出:
3 the
2 dog
1 brown
1 fox
1 jumps
1 lazy
1 over
1 quick
1 sleeps
补充 8:顺带一提:迭代器(ch13 详讲)
来源:08 章。请在读完相关正文后再练习;本节组合多个章节的内容。
三个集合最美的地方是它们都能用迭代器链:
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 取偶数 → 乘 2 → 收集
let result: Vec<i32> = numbers
.iter()
.filter(|&&n| n % 2 == 0)
.map(|&n| n * 2)
.collect();
println!("{result:?}"); // [4, 8, 12, 16, 20]
// 更清爽的写法
let result2: Vec<i32> = numbers
.iter()
.copied() // 把 &i32 变成 i32
.filter(|n| n % 2 == 0)
.map(|n| n * 2)
.collect();
println!("{result2:?}");
// 求和、最大、最小
println!("和 {}", numbers.iter().sum::<i32>());
println!("最大 {:?}", numbers.iter().max());
}
|&&n| 这种看着吓人的写法:因为 iter() 给的是 &i32,filter 又给 &&i32,
所以要解两层。写的时候编译器会告诉你该写几层,不用背。
注意迭代器是惰性的:
fn main() {
let v = vec![1, 2, 3];
// 这行什么都不做!
v.iter().map(|n| {
println!("被调用了 {n}");
n * 2
});
println!("--- 上面没有输出 ---");
// 需要一个"消费者"才会执行
let doubled: Vec<i32> = v.iter().map(|n| n * 2).collect();
println!("{doubled:?}");
}
缺消费者(collect / sum / for / count / any / find)是新手常见困惑:
“我写了 map 怎么没反应?”
补充 9:用自定义 enum 统一多种错误
来源:09 章。请在读完相关正文后再练习;本节组合多个章节的内容。
进阶补充:下面的 impl From<...> for MyError 是实现类型转换 trait,
ch10 会解释 trait 与 impl。本页在正文之后阅读;trait 的定义和实现已经在第 10 章解释。
From<E> 是类型转换 trait,from 接收一个 E 并返回目标类型。
? 传播不同类型的错误时,通过对应的 From 实现构造当前函数需要的错误。
一个函数里可能出多种错(读文件失败、解析失败),用枚举把它们包起来:
use std::fs;
use std::num::ParseIntError;
#[derive(Debug)]
enum MyError {
Io(std::io::Error),
Parse(ParseIntError),
}
// 实现 From,? 才能自动转换
impl From<std::io::Error> for MyError {
fn from(e: std::io::Error) -> Self {
MyError::Io(e)
}
}
impl From<ParseIntError> for MyError {
fn from(e: ParseIntError) -> Self {
MyError::Parse(e)
}
}
// 注意:这里**没有**手写任何转换,两个 ? 各自自动转成 MyError
fn read_number(path: &str) -> Result<i32, MyError> {
let content = fs::read_to_string(path)?; // io::Error → MyError::Io
let n: i32 = content.trim().parse()?; // ParseIntError → MyError::Parse
Ok(n)
}
fn main() {
match read_number("/definitely/not/here") {
Ok(n) => println!("读到 {n}"),
Err(MyError::Io(e)) => println!("读文件失败:{e}"),
Err(MyError::Parse(e)) => println!("解析失败:{e}"),
}
}
这段代码值得慢慢读 —— 它展示了 Rust 错误处理的核心机制:
? + From 让错误类型自动“向上归并“,同时保持类型安全(调用方能 match 具体是哪种错误)。
调用方也能按种类处理:
match read_number("config.txt") {
Ok(n) => println!("读到 {n}"),
Err(MyError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {
println!("配置文件不存在,用默认值");
}
Err(e) => println!("其他错误:{e}"),
}
补充 10:偷懒但常用的写法:Box<dyn Error>
来源:09 章。请在读完相关正文后再练习;本节组合多个章节的内容。
进阶补充:Box 拥有装箱值(ch15),dyn Error 表示按 Error 接口使用不同错误类型(ch18)。
第 15 章已经解释 Box,第 18 章已经解释 trait 对象。这里组合两者保存错误。
上面的 From 实现很啰嗦。如果调用方不需要区分错误种类,可以用 Box<dyn Error>:
use std::error::Error;
use std::fs;
// 任何实现了 Error 的类型都能自动转成 Box<dyn Error>
fn read_number(path: &str) -> Result<i32, Box<dyn Error>> {
let content = fs::read_to_string(path)?; // 自动装箱
let n: i32 = content.trim().parse()?; // 自动装箱
Ok(n)
}
fn main() {
match read_number("/definitely/not/here") {
Ok(n) => println!("读到 {n}"),
Err(e) => println!("出错了:{e}"), // 只打印,不区分种类
}
}
什么时候用哪个:
| 场景 | 用什么 |
|---|---|
| 写库,调用方需要区分错误 | 自定义 enum(或 thiserror 帮你生成) |
| 写应用,只需要打印/记录日志 | Box<dyn Error> 或 anyhow |
| 快速原型、测试 | Box<dyn Error> |
thiserror 和 anyhow 是两个常用的 crate(本仓库的依赖里有):
// thiserror:自动生成 From 和 Display,写库时用
#[derive(Debug, thiserror::Error)]
enum MyError {
#[error("读文件失败:{0}")]
Io(#[from] std::io::Error), // #[from] 自动生成 From impl
#[error("解析失败:{0}")]
Parse(#[from] ParseIntError),
}
// anyhow:写应用时用,任何错误都能 .context("做了什么") 加说明
use anyhow::{Context, Result};
fn load(path: &str) -> Result<i32> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("读取 {path} 失败"))?;
let n: i32 = content.trim().parse().context("内容不是数字")?;
Ok(n)
}
新手建议:先手写 From 实现几遍(理解机制),然后再用 thiserror(省事)。
补充 11:一个容易记错的点
来源:09 章。请在读完相关正文后再练习;本节组合多个章节的内容。
String 可以 ? 进 Box<dyn Error>,但 String 不是 Error:
use std::error::Error;
fn main() {
// ✔ 能转换(标准库有 From<String> for Box<dyn Error>)
fn takes_boxed(e: Box<dyn Error>) -> String {
e.to_string()
}
println!("{}", takes_boxed(Box::from("出错了")));
// ✘ 但 String 本身不实现 Error —— 泛型约束 E: Error 时用不了
// fn takes_error<E: Error>(_: E) {}
// takes_error(String::from("x")); // E0277: String: Error is not satisfied
}
准确说法:“String 可以当错误“应限定为”可以 ?/into() 进 Box<dyn Error>“。
需要“能被 match、能区分种类“的错误时,仍然必须定义自己的类型。
补充 12:存储不同类型的闭包
来源:13 章。请在读完相关正文后再练习;本节组合多个章节的内容。
两条出路:第 20 章的函数指针,以及第 15、18 章的 Box 与 trait 对象。
fn main() {
// 出路一:无捕获的闭包能"退化"成 fn 指针(8 字节)
let fns: Vec<fn() -> i32> = vec![|| 1, || 2, || 3];
let sum: i32 = fns.iter().map(|f| f()).sum();
println!("fn 指针 Vec 求和 {sum}");
// 出路二:捕获了环境就装箱成 dyn Fn(有堆分配和动态转发开销)
let prefix = String::from("结果");
let boxes: Vec<Box<dyn Fn(i32) -> String>> = vec![
Box::new(move |x| format!("{prefix}: {x}")),
Box::new(|x| format!("[debug] {x}")),
];
for f in &boxes {
println!("{}", f(1));
}
}
输出:
fn 指针 Vec 求和 6
结果: 1
[debug] 1
区分标准很清楚:捕获了环境的闭包不能转换成普通 fn 指针;统一存储不同闭包时,可以用 Box<dyn Fn..>。无捕获闭包可以转换成 fn 指针。
捕获了还想当 fn 指针用,编译器会明说:
fn main() {
let a = 1;
let ops: Vec<fn(i32) -> i32> = vec![|x| x + 1, |x| x + a];
for op in &ops {
println!("{}", op(5));
}
}
error[E0308]: mismatched types
--> src/main.rs:3:52
|
3 | let ops: Vec<fn(i32) -> i32> = vec![|x| x + 1, |x| x + a];
| ^^^^^^^^^ expected fn pointer, found closure
|
= note: expected fn pointer `fn(i32) -> i32`
found closure `{closure@src/main.rs:3:52: 3:55}`
note: closures can only be coerced to `fn` types if they do not capture any variables
顺带一个必须知道的细节:Box<dyn FnMut()> 会一直握着捕获变量的可变借用,
直到这个 Box 被 drop。所以想在外面读那个变量,得先 drop 掉它:
fn main() {
let mut n = 0;
let mut f: Box<dyn FnMut()> = Box::new(|| {
n += 1;
});
f();
println!("{n}"); // f 还活着,n 还是被可变借走的
}
error[E0502]: cannot borrow `n` as immutable because it is also borrowed as mutable
--> src/main.rs:7:16
|
3 | let mut f: Box<dyn FnMut()> = Box::new(|| {
| -- mutable borrow occurs here
4 | n += 1;
| - first borrow occurs due to use of `n` in closure
...
7 | println!("{n}"); // f 还活着,n 还是被可变借走的
| ^ immutable borrow occurs here
8 | }
| - mutable borrow might be used here, when `f` is dropped and runs the destructor for type `Box<dyn FnMut()>`
修法是让 Box 先被 drop,把借用还回去:
fn main() {
let mut n = 0;
{
let mut f: Box<dyn FnMut()> = Box::new(|| n += 1);
f();
f();
} // Box 在作用域结束时 drop,借用还回去
println!("{n}"); // 2
}
补充 13:Box 与 trait 对象的空间
来源:15 章。请在读完相关正文后再练习;本节组合多个章节的内容。
Box<dyn Trait> 是胖指针。 当 T: Sized 时,Box<T> 是一个字长,Box<dyn Trait> 是两个字长:
一个指向数据,一个指向虚表(vtable)。多出来的这个字长换到的是“动态派发“。
trait Speak {
fn say(&self) -> String;
}
struct Dog;
struct Robot;
impl Speak for Dog {
fn say(&self) -> String {
String::from("汪")
}
}
impl Speak for Robot {
fn say(&self) -> String {
String::from("滴")
}
}
fn main() {
// 同一个 Vec 里放不同的具体类型:靠 trait 对象
let all: Vec<Box<dyn Speak>> = vec![Box::new(Dog), Box::new(Robot)];
for s in &all {
println!("{}", s.say());
}
println!("Box<dyn Speak> = {}", std::mem::size_of::<Box<dyn Speak>>());
println!("&dyn Speak = {}", std::mem::size_of::<&dyn Speak>());
println!("Box<u8> = {}", std::mem::size_of::<Box<u8>>());
}
汪
滴
Box<dyn Speak> = 16
&dyn Speak = 16
Box<u8> = 8
Box<dyn Trait> 的完整用法(什么时候该用它、和泛型怎么选)留到讲 trait 对象的那一节,
这里只要记住:它比普通 Box 宽一倍,而且通常经由虚表调用,会影响内联机会;编译器知道实际类型时也可能消除间接调用。
补充 14:为什么 Rc 不是 Send
来源:15 章。请在读完相关正文后再练习;本节组合多个章节的内容。
Rc 的计数是一个普通整数,没有原子性。两个线程同时 Rc::clone 同一个值,
计数就会算错 —— 要么提前释放(use-after-free),要么永远不释放。所以编译器直接禁止:
use std::rc::Rc;
fn main() {
let x = Rc::new(5);
std::thread::spawn(move || {
let _ = *x;
})
.join()
.unwrap();
}
error[E0277]: `Rc<i32>` cannot be sent between threads safely
--> rc_not_send.rs:5:24
|
5 | std::thread::spawn(move || {
| ------------------ ^------
| | |
| _____|__________________within this `{closure@rc_not_send.rs:5:24: 5:31}`
| | |
| | required by a bound introduced by this call
6 | | let _ = *x;
7 | | })
| |_____^ `Rc<i32>` cannot be sent between threads safely
|
= help: within `{closure@rc_not_send.rs:5:24: 5:31}`, the trait `Send` is not implemented for `Rc<i32>`
note: required because it's used within this closure
note: required by a bound in `spawn`
|
128 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
(中间省略了几行 --> 定位信息。)报错很长,但关键只有一句:
the trait Send is not implemented for Rc<i32>。
读报错时有个规律:cannot be **sent** between threads safely 缺的是 Send,
cannot be **shared** between threads safely 缺的是 Sync。四个类型正好凑成一张表:
| 类型 | Send | Sync | 说明 |
|---|---|---|---|
Rc<T> | ✗ | ✗ | 计数不是原子的 |
RefCell<T> | 当 T: Send 时 ✓ | ✗ | 整个值能送进线程,但不能被两个线程同时借用 |
Cell<T> | 当 T: Send 时 ✓ | ✗ | 同上 |
Mutex<T> | 当 T: Send 时 ✓ | 当 T: Send 时 ✓ | 通过锁同步跨线程访问 |
RefCell 那一行最容易记反:它不是线程安全的,但它确实可以被 move 进另一个线程
(需要内部 T: Send,且没有尚未结束的借用)。Arc<T> 就是“原子计数的 Rc“,细节在 ch16 讲并发时展开。
补充 15:和 Mutex 最重要的差别:RefCell 不会“中毒“
来源:15 章。请在读完相关正文后再练习;本节组合多个章节的内容。
持锁期间发生可展开的 panic 后,Mutex 通常会中毒(lock() 返回 Err(PoisonError))。中毒检测是尽力而为,不能当成内存安全的保证。
下面 AssertUnwindSafe 是对 catch_unwind 的手动声明:调用方接受并检查捕获 panic 后留下的数据状态;它不会回滚已经发生的修改。
中毒标记提醒后来者检查“数据可能不一致“这件事。RefCell 不会 —— panic 之后照常可用:
use std::cell::RefCell;
use std::panic::{AssertUnwindSafe, catch_unwind};
fn main() {
let c = RefCell::new(vec![1]);
let r = catch_unwind(AssertUnwindSafe(|| {
let mut m = c.borrow_mut();
m.push(2);
panic!("boom"); // RefMut 在 unwind 里被 drop,借用计数归零
}));
println!("panic 被抓到了:{}", r.is_err());
// 解包之后照常借用 —— 数据停在"半更新"状态,没人提醒你
println!("{:?}", *c.borrow());
}
panic 被抓到了:true
[1, 2]
数据是“半更新“的(2 已经进去了),但没人阻止你继续用。
这就是“用运行时检查换灵活性“要付的账:要么改完,要么不改,得你自己保证。
(上面只贴了 stdout。panic 的原始信息 boom 仍然会被 panic hook 打到 stderr ——
抓不抓得到和打不打印是两回事。)
(顺带:&RefCell<T> 不是 UnwindSafe(缺的是 RefUnwindSafe,报错点在内部的 UnsafeCell),
所以 catch_unwind 包住它必须加 AssertUnwindSafe —— 这正是“这里需要你签字画押“的提示。)
RefCell<T> 在 T: Send 时可以把整个值转移到另一线程,但它不是 Sync,
不能把同一个 RefCell 的共享引用送给多个线程使用。
被两个线程同时借用会在运行时把计数搞乱,所以编译器直接拒绝:
use std::cell::RefCell;
fn main() {
let c = RefCell::new(5);
std::thread::scope(|s| {
s.spawn(|| {
let _ = c.borrow();
});
});
}
error[E0277]: `RefCell<i32>` cannot be shared between threads safely
--> refcell_not_sync.rs:6:17
|
6 | s.spawn(|| {
| ___________-----_^
| | |
| | required by a bound introduced by this call
7 | | let _ = c.borrow();
8 | | });
| |_________^ `RefCell<i32>` cannot be shared between threads safely
|
= help: the trait `Sync` is not implemented for `RefCell<i32>`
= note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
= note: required for `&RefCell<i32>` to implement `Send`
(“cannot be shared” → 缺 Sync,不是缺 Send。)
还有一个坑:Ref / RefMut 靠 Drop 还计数,泄漏借用守卫会使对应的动态借用计数不再归还:
泄漏 RefMut 会使后续 borrow / borrow_mut 都失败;泄漏 Ref 会阻止后续可变借用。
use std::cell::RefCell;
fn main() {
let c = RefCell::new(5);
std::mem::forget(c.borrow_mut()); // 借用计数永远不会减回去
println!("try_borrow 失败 = {}", c.try_borrow().is_err());
println!("try_borrow_mut 失败 = {}", c.try_borrow_mut().is_err());
}
try_borrow 失败 = true
try_borrow_mut 失败 = true
补充 16:为什么需要 async:先算一笔线程的账
来源:17 章。请在读完相关正文后再练习;本节组合多个章节的内容。
设想一个聊天服务,同时维持 2 万个连接。每个连接大部分时间都在等:等客户端发消息,等网络把数据送出去。 这是典型的 IO 密集(I/O-bound)场景 —— CPU 几乎没有活干,时间全花在等待上。
用线程的写法很自然:一个连接一个线程,每个线程阻塞在 recv() 上。
问题在于线程很贵。这不是形容词,是可以量的:
运行:cargo run --release --bin ch17_thread_vs_task_cost -- thread 12000
cargo run --release --bin ch17_thread_vs_task_cost -- thread 20000
cargo run --release --bin ch17_thread_vs_task_cost -- task 100000
线程 12000 个,耗时 652.843861ms(平均 54.403µs/个)
新增地址空间 32322 MB(每个 2758 KB),新增常驻内存 112 MB
第 19125 个线程起不来:Resource temporarily unavailable (os error 11)
线程 19124 个,耗时 1.118809555s(平均 58.502µs/个)
新增地址空间 46687 MB(每个 2500 KB),新增常驻内存 179 MB
任务 100000 个,耗时 36.243279ms(平均 362ns/个)
新增地址空间 37 MB(每个 0 KB),新增常驻内存 37 MB
(16 核 Linux 上的实测值,数字和机器强相关;每种模式都是“起 N 个什么都不干的并发单位“, 测的是纯创建成本。读者机器上的具体上限会不一样,任务状态大小、资源上限和线程成本都取决于机器及程序,不能当作通用保证。)
第三条是这次实验里最有说服力的一条:这台机器上,19 125 个线程就是天花板,
再起一个直接 os error 11(EAGAIN)—— 而 10 万个异步任务只花了 37 MB。
| 线程 | tokio 任务 | |
|---|---|---|
| 12 000 个要多久 | 653 ms | 3.6 ms |
| 一个占多少地址空间 | 2 758 KB(默认预留 2 MiB 栈) | 约 380 字节(堆上) |
| 10 万个 | 起不到(1.9 万个就 EAGAIN 了) | 37 MB,实测能起 |
线程贵在三处:
- 栈:
std::thread默认给每个线程预留 2 MiB 栈。这部分是地址空间,不是立刻用掉的内存, 但 2 万个线程就是 40 GB 地址空间 —— 还没开始干活就先没了。 (Builder::stack_size能调小,但真实业务代码几十 KB 栈是不够用的。) - 创建和调度:每个线程是一个内核对象,创建要进内核,切换也要进内核。上表里 54 µs 起一个线程, 是 async 任务的 150 倍。
- 数量上限:内核、内存、cgroup 都有上限,撞上就是
EAGAIN。 ch16 的结论是“几百个线程没问题,几万个就不合适了“ —— 现在你有具体数字了。
async 的答案是:别让每个并发单位都占一条线程。 把“这件事在等 IO“表示成一个可以在任意位置暂停/恢复的状态机,让运行时用少量线程去跑成千上万个状态机。 上面量到的约 380 字节反映了这个样例的任务状态及运行时开销,不是所有任务的固定大小。
但 async 不是“更快的线程“:
- CPU 密集的计算用 async 不会变快(没有并行的成分,还要付状态机的开销)
- 它引入了运行时依赖、一类新的 bug(这一节后半段讲的全是它们)、更难读的调用栈
- 只有几路并发时,
std::thread/thread::scope往往更简单
什么时候值得付这个代价:IO 密集 + 高并发(网络服务、爬虫、网关),或者整个生态已经是 async 的
(用了 reqwest / axum / sqlx,那你就得在 async 里写)。
补充 17:手写一个 executor(只用 std)
来源:17 章。请在读完相关正文后再练习;本节组合多个章节的内容。
运行时通过轮询 future 推进任务。下面只演示轮流推进两个会主动让出的任务,不是通用执行器:
Wake 定义收到唤醒通知时要做什么,Waker::from 把实现包装成通知入口;Context::from_waker 把该入口交给 poll。这里的 NoopWaker 故意不做调度,循环直接轮询,因此只适合这个确定会很快就绪的例子,不能用于真正等待 I/O 的程序。
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
// 一个"这次 Pending、下次 Ready"的 future,用来制造一个 await 点
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref(); // "我下次就能好"
Poll::Pending
}
}
}
async fn task(name: &str) {
println!("{name}: 第一步");
YieldOnce(false).await;
println!("{name}: 第二步");
YieldOnce(false).await;
println!("{name}: 完成");
}
struct NoopWaker;
impl Wake for NoopWaker {
fn wake(self: Arc<Self>) {}
}
fn main() {
let waker = Waker::from(Arc::new(NoopWaker));
let mut cx = Context::from_waker(&waker);
// 两个 future("任务")都只是创建,还没有跑
let mut a = Box::pin(task("A"));
let mut b = Box::pin(task("B"));
// 玩具 executor:轮流 poll 两个 future,直到都 Ready
for round in 1..=4 {
println!("--- 第 {round} 轮 ---");
let pa = a.as_mut().poll(&mut cx);
let pb = b.as_mut().poll(&mut cx);
if pa.is_ready() && pb.is_ready() {
break;
}
}
}
输出:
--- 第 1 轮 ---
A: 第一步
B: 第一步
--- 第 2 轮 ---
A: 第二步
B: 第二步
--- 第 3 轮 ---
A: 完成
B: 完成
这个例子展示了一种异步并发的推进过程:一条线程,两个任务交替推进。 “并发“不等于“并行” —— 这里从头到尾只有一条线程,谁也没有和谁同时执行。
真运行时要复杂得多(有多个 worker 线程、任务队列、timer、IO 事件通知,Pending 时把线程挂起而不是忙等),
但**“poll 到 Pending 就换下一个”**这个核心没有变。
补充 18:Pin:为什么会有这么个别扭的东西
来源:17 章。请在读完相关正文后再练习;本节组合多个章节的内容。
先说结论:日常写业务代码,你几乎不需要手写 Pin。 但要知道它为什么存在,否则看错误信息会一头雾水。
状态机可能是自引用的
看这个 async fn:
#![allow(unused)]
fn main() {
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.0 {
Poll::Ready(())
} else {
self.0 = true;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
struct NoopWaker;
impl Wake for NoopWaker {
fn wake(self: Arc<Self>) {}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let waker = Waker::from(Arc::new(NoopWaker));
let mut cx = Context::from_waker(&waker);
let mut fut = Box::pin(fut);
loop {
if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
return v;
}
std::thread::yield_now(); // 玩具实现:忙等
}
}
async fn work() -> usize {
let mut v = vec![1, 2, 3];
let r = &mut v; // r 借用 v
YieldOnce(false).await; // ← r 跨过了这个 await,还活着
r.push(4);
v.len()
}
let n = block_on(work());
assert_eq!(n, 4);
}
这段代码是合法且安全的。但想想编译器生成的状态机里有什么:
变量 v 和指向 v 的引用 r 在同一个结构体里(r 活过了 await 点,必须被存进去)。
结构体里存着指向自己的指针 —— 这叫自引用(self-referential)。
自引用结构体本身没问题,问题是不能移动:一旦移动,v 换了地址,r 还指着旧地址,就成了悬垂指针
(而且这是安全代码,编译器不能允许它 UB)。
Pin<P> 约束指针指向的值,而不是说这个指针包装本身不能移动。
对 T: !Unpin,安全代码不能从 Pin<&mut T> 随意拿到普通 &mut T,
否则可以通过替换把固定的值搬走;访问字段需要正确的投影方式。
对 T: Unpin,可以安全地用 get_mut() 得到 &mut T,不再受这项固定位置限制。
试试搬走它:
use std::pin::Pin;
async fn work() -> u32 {
1
}
fn main() {
let mut fut = Box::pin(work());
let moved = *fut; // 想把里面的 future 搬出来
drop(moved);
}
error[E0507]: cannot move out of dereference of `Pin<Box<impl Future<Output = u32>>>`
--> pinmove.rs:9:17
|
9 | let moved = *fut; // 想把里面的 future 搬出来
| ^^^^ move occurs because value has type `impl Future<Output = u32>`, which does not implement the `Copy` trait
|
help: consider removing the dereference here
|
9 - let moved = *fut; // 想把里面的 future 搬出来
9 + let moved = fut; // 想把里面的 future 搬出来
记住这三句就够了
Pin保证“不再移动“,因为状态机可能是自引用的- 大多数类型是
Unpin的(移动它们完全没问题),编译器生成的 async 状态机通常不是;自己定义的固定位置类型也可能不是 - 需要把可能
!Unpin的 future 固定在堆上时,可以写Box::pin(fut);.await会自动处理 pin,你不用管
补充 19:运行时才知道数量:join_all 与固定 future
来源:17 章。请在读完相关正文后再练习;本节组合多个章节的内容。
join!(a, b) 的参数数量写在代码里。如果数量来自运行时集合,
可以用 futures::future::join_all:
// 需要 futures 和 tokio;完整版本在 examples/39_async_channels_and_groups.rs。
use futures::future::join_all;
use std::future::Future;
use std::pin::Pin;
#[tokio::main(flavor = "current_thread")]
async fn main() {
let mut jobs: Vec<Pin<Box<dyn Future<Output = u32>>>> = Vec::new();
jobs.push(Box::pin(async { 7 }));
jobs.push(Box::pin(async { 9 }));
let results = join_all(jobs).await;
assert_eq!(results, [7, 9]);
}
每一个独立的 async { ... } 都生成自己的类型,即使输出同为 u32,
也不能直接塞进同一个普通 Vec。dyn Future<Output = u32> 统一接口,
Box 提供间接存储,Pin 固定堆上 future 的位置。
Box<dyn Future<...>> 本身还不够;异步块通常不满足 Unpin,因此这里用 Box::pin。
如果所有 future 都由同一个 async fn 或同一个闭包表达式生成,
元素类型一致,通常可以直接收集到 Vec<_>,不必装箱。
join_all 在当前任务里推进集合,不会自动创建新线程或新任务;
结果按输入顺序返回,和完成顺序无关。
补充 20:async trait 与动态分发
来源:17 章。请在读完相关正文后再练习;本节组合多个章节的内容。
带有 async fn 方法的 trait 不能直接做成 dyn Greeter。每个实现生成的 future 类型可能不同,
动态分发的调用方没有一个固定的返回类型可用。下面的代码应当编译失败:
#![allow(unused)]
fn main() {
trait Greeter {
async fn greet(&self) -> String;
}
fn use_dyn(_greeter: &dyn Greeter) {}
}
若确实需要把不同实现放进同一个容器,就把返回的 future 装箱,
在 trait 方法签名中明确返回类型。examples/38_stream_and_traits.rs 同时运行了
泛型版和 Box<dyn DynGreeter> 版,验证输出相同。装箱多一次分配和动态派发;
只调用一种已知实现时优先使用泛型。若 boxed future 要交给多线程
tokio::spawn,还需按其约束加入 Send 和足够长的生命周期。
补充 21:反过来的限制:dyn 上不能调用泛型方法
来源:18 章。请在读完相关正文后再练习;本节组合多个章节的内容。
dyn Trait 靠一张固定大小的 vtable 工作。
如果 trait 里有一个泛型方法,那这个方法会有无限多个实例化(T 可以是任何类型),
vtable 装不下。这个限制在 Rust 里叫 dyn 兼容性(dyn compatibility)。
版本差异(重要):这条规则旧名字叫对象安全(object safety)。 Rust 1.99 的报错里已经搜不到 “object safe” 这个词了,改成了 dyn compatible。 错误码没变,还是
E0038。看老文章或老书时注意这个术语断代。
trait State {
fn ok(&self) -> i32;
// 泛型方法 —— 它会让整个 trait 失去 dyn 兼容性
fn generic<T: std::fmt::Debug>(&self, t: T);
}
fn use_it(x: &dyn State) -> i32 {
x.ok()
}
fn main() {}
error[E0038]: the trait `State` is not dyn compatible
--> notdyn.rs:6:15
|
6 | fn use_it(x: &dyn State) -> i32 { x.ok() }
| ^^^^^^^^^^ `State` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> notdyn.rs:2:8
|
1 | trait State {
| ----- this trait is not dyn compatible...
2 | fn ok(&self) -> i32;
...
4 | fn generic<T: std::fmt::Debug>(&self, t: T);
| ^^^^^^^ ...because method `generic` has generic type parameters
|
= help: consider moving `generic` to another trait
where Self: Sized 是解药:加了它,这个方法就“声明自己不进 vtable“,
trait 重新变得 dyn 兼容。代价是这个方法在 dyn Trait 上调用不了:
trait State {
fn ok(&self) -> i32;
/// where Self: Sized —— 不进 vtable,因此不影响 dyn 兼容性
fn generic<T: std::fmt::Debug>(&self, t: T)
where
Self: Sized,
{
println!("{t:?}");
}
}
struct A;
impl State for A {
fn ok(&self) -> i32 {
1
}
}
fn main() {
let a = A;
let dyn_state: &dyn State = &a;
assert_eq!(dyn_state.ok(), 1); // ok
a.generic(42); // 具体类型上能调
// dyn_state.generic(42); // ← 编译不过
}
试着在 dyn_state 上调 generic:
error: the `generic` method cannot be invoked on a trait object
--> selfsized.rs:13:7
|
3 | fn generic<T: std::fmt::Debug>(&self, t: T) where Self: Sized { println!("{t:?}"); }
| ----- this has a `Sized` requirement
...
13 | s.generic(1i32);
| ^^^^^^^
其他常见的“破坏 dyn 兼容性“的写法,遇到 E0038 时按这张表对号入座:
| 写法 | 为什么不行 | 修法 |
|---|---|---|
fn f<T>(&self, t: T) | 泛型方法要有无限多份实现 | where Self: Sized,或移到另一个 trait |
fn f() -> Self | 返回类型在 vtable 里没法统一大小 | 改成返回 Box<dyn Trait>,或 where Self: Sized |
关联常量 const N: usize | 每个实现者都能给不同的值 | 改成方法 fn n(&self) -> usize |
fn f(&self) -> Self::Item(关联类型) | 编译器不知道该用哪个 Item | 写清 dyn Trait<Item = i32>(报的是 E0191,不是 E0038) |
补充 22:但是:默认方法救不了重复代码
来源:18 章。请在读完相关正文后再练习;本节组合多个章节的内容。
request_review 和 approve 在两个状态(PendingReview、Published)里
都写着 self —— 明显的重复。直觉上应该在 trait 里给个默认实现:
#![allow(unused)]
fn main() {
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
}
}
error[E0277]: the size for values of type `Self` cannot be known at compilation time
--> default_self.rs:2:60
|
2 | fn request_review(self: Box<Self>) -> Box<dyn State> { self }
| ^^^^ doesn't have a size known at compile-time
|
= note: required for the cast from `Box<Self>` to `Box<(dyn State + 'static)>`
help: consider further restricting `Self`
|
2 | fn request_review(self: Box<Self>) -> Box<dyn State> where Self: Sized { self }
| +++++++++++++++++
编译器给的 where Self: Sized 建议是个陷阱:加是能编译,
但这个方法就不能从 dyn State 上调用了(上一节刚验证过),
而 Post::request_review 正是要通过 dyn 调它 —— 等于自断经脉。
补充:跨章节的智能指针选择
本节在学完线程与 trait 对象之后阅读。
15.8 决策表:六个类型怎么选
到这一步,你手里有六个工具。选错的代价是“多一次原子操作“到“生产环境 panic“不等, 所以这张表值得贴在显示器边上:
| 我想…… | 用什么 | 为什么 | 代价 |
|---|---|---|---|
| 放一个递归类型(链表、树、AST) | Box<T> | 编译期要确定大小,指针大小固定 | 一次堆分配、一次跳转 |
在 Vec 里放不同的具体类型 | Box<dyn Trait> | 动态派发 | 胖指针(常见布局为 2 字长)、通常通过虚表调用 |
让函数收 &str 也能收 &String | 形参写 &str | 调用点自动做强制转换 | 只发生在转换点,无运行时开销 |
| 让多个地方只读共享 | Rc<T> | 引用计数,单线程 | 计数开销;!Send |
跨线程共享,且 T: Send + Sync | Arc<T> | 原子引用计数 | 原子操作比普通计数慢 |
| 单线程共享可变状态 | Rc<RefCell<T>> | 借用检查推到运行时 | 运行时 panic 风险 |
| 跨线程共享可变状态 | Arc<Mutex<T>> | 锁 + 原子计数 | 死锁、锁竞争、中毒 |
| 只要一个可变的小格子 | Cell<T> | 不借用,整存整取 | 只适合 Copy(或整存整取) |
| 让一部分引用不参与所有权 | Weak<T> | 不加 strong_count,打断环 | 用之前必须 upgrade() 判空 |
需要在 &self 里改自己 | RefCell<T> / Cell<T> | 内部可变性 | 运行时借用检查 |
| 在析构时做清理 | 实现 Drop | 编译器自动插入 | 别在 Drop 里 panic / 阻塞 |
最容易选错的两格:
Rc<RefCell<T>>和Arc<Mutex<T>>不是“基础版和升级版“,是两个世界。 判据只有一条:这个值会不会跨线程。会才用右边,不会就用左边 —— 别提前上原子操作和锁。Cell<T>不是“更快的RefCell“。它连&T都给不出来,所以常用于Copy的小值;也能通过replace或take整体取换非 Copy 值。
选之前先问三个问题(按顺序):
- 这个值真的需要共享所有权吗?能不能让一个所有者 + 若干借用解决?
—— 能的话,
Box或者干脆不用智能指针。 - 需要修改吗?—— 不需要就
Rc/Arc;需要就加RefCell/Mutex/Cell。 - 会跨线程共享所有权吗?—— 需要引用计数的共享所有权时用
Arc,并把内部可变性换成Mutex/RwLock。
三条都问完还没有答案的情况很少。真遇到了,说明问题更可能出在数据结构设计上, 而不是“该选哪个智能指针“。
试一试(综合判断)
-
一棵 DOM 树:父节点要能拿到子节点,子节点要能拿到父节点。用什么组合?
-
一个被整个程序共享的只读配置。用什么?
-
一个多线程计数器。用什么?
-
一个解析出来的 AST,节点会互相引用(表达式引用变量定义)。先想清楚“谁拥有谁“, 再决定用不用智能指针。
-
一个
struct Session { last_error: Option<String> },有一个&self方法要记录错误。 用Cell还是RefCell? -
一条双向链表。写出节点类型,并指出哪一半方向是
Weak(如果不需要反向遍历, 是不是可以根本不用Rc?) -
判断练习:把下面六个需求对上类型(
Box/Rc/Arc/RefCell/Cell/Mutex):- 单线程下多个观察者共享一个可变的计数器
- 递归的 JSON 值枚举
- 一个需要跨线程共享的日志缓冲区
- 一个
&self方法里自增的u32命中次数 - 一个在
&self方法里push的Vec<String> - 只读共享给同线程的多个视图
dyn 兼容性判断练习
先阅读本附录中 dyn 兼容性与 Sized 的补充说明,再完成下面的练习。
判断练习:下面哪些会让 trait 失去 dyn 兼容性?(先猜,再用 &dyn 验证)
fn area(&self) -> f64;fn scale(&self, factor: f64) -> Self;fn describe<T: std::fmt::Display>(&self, extra: T);fn name(&self) -> String { "无名".to_string() }(有默认实现)