上一节练习答案要点
要点:clamp 用 v.max(lo).min(hi),lo > hi 用断言守卫钉成 panic(或选定交换语义,总之要测住);表驱动 (v, lo, hi, 期望) 循环、消息带输入,lo == hi 必测。parse_port 先 parse::<i32>() 再查范围,成功、非数字、越界三类各有断言。汇总代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
| // 上一节练习答案要点:clamp 表驱动 + parse_port + should_panic + 三道思考题
use std::panic;
fn clamp(v: i32, lo: i32, hi: i32) -> i32 {
assert!(lo <= hi, "下界不能大于上界,收到 lo={}, hi={}", lo, hi);
v.max(lo).min(hi)
}
fn parse_port(s: &str) -> Result<u16, String> {
let n: i32 = s.parse().map_err(|_| format!("不是数字:{s}"))?;
if (1..=65535).contains(&n) { Ok(n as u16) } else { Err(format!("端口越界:{n}")) }
}
#[derive(PartialEq)] // 故意不 derive Debug:思考题 1 的主角
struct Point { x: i32, y: i32 }
fn main() {
// clamp 表驱动:(v, lo, hi, 期望),含 lo == hi 边界
let cases = [(5, 0, 10, 5), (-3, 0, 10, 0), (15, 0, 10, 10), (7, 7, 7, 7), (0, 7, 7, 7)];
for (v, lo, hi, want) in cases {
assert_eq!(clamp(v, lo, hi), want, "clamp({v}, {lo}, {hi}) 应为 {want}");
}
println!("clamp 表驱动 5 组用例通过(含 lo == hi 边界)");
// parse_port:成功与两种失败
assert_eq!(parse_port("8080").unwrap(), 8080);
assert_eq!(parse_port("abc").unwrap_err(), "不是数字:abc");
assert_eq!(parse_port("70000").unwrap_err(), "端口越界:70000");
println!("parse_port 成功/非数字/越界三类用例通过");
// should_panic 模拟:lo > hi 触发守卫,消息含“下界不能大于上界”
assert!(panic::catch_unwind(|| clamp(1, 10, 0)).is_err());
println!("should_panic 模拟通过:clamp(1, 10, 0) 触发守卫 panic");
// 思考题 1:没有 Debug 时用 assert! 比较相等(只需 PartialEq),或逐字段 assert_eq!
let a = Point { x: 1, y: 2 };
let b = Point { x: 1, y: 2 };
assert!(a == b, "Point 相等性检查(无 Debug 时 assert! 不需要打印值)");
println!("思考题 1:无 Debug 用 assert!(a == b)(只依赖 PartialEq),或给类型 derive Debug 后用 assert_eq!");
println!("思考题 2:单独过、整套偶发失败多半是共享状态(全局变量/文件/环境变量/端口)被并行测试互相污染;");
println!(" 用 cargo test -- --test-threads=1 对比是否稳定,再查每个测试是否自备数据");
println!("思考题 3:给 #[should_panic] 加 expected 子串钉住 panic 原因;消息措辞变更时同步更新,误报就会现形");
}
|
输出:
1
2
3
4
5
6
7
| clamp 表驱动 5 组用例通过(含 lo == hi 边界)
parse_port 成功/非数字/越界三类用例通过
should_panic 模拟通过:clamp(1, 10, 0) 触发守卫 panic
思考题 1:无 Debug 用 assert!(a == b)(只依赖 PartialEq),或给类型 derive Debug 后用 assert_eq!
思考题 2:单独过、整套偶发失败多半是共享状态(全局变量/文件/环境变量/端口)被并行测试互相污染;
用 cargo test -- --test-threads=1 对比是否稳定,再查每个测试是否自备数据
思考题 3:给 #[should_panic] 加 expected 子串钉住 panic 原因;消息措辞变更时同步更新,误报就会现形
|
三道思考题:assert_eq! 需要 Debug 是为了失败时打印左右值,没有就退到只依赖 PartialEq 的 assert!(a == b);整套偶发失败先怀疑并行共享状态,--test-threads=1 是最快分诊;should_panic 不写 expected 只验“崩了”、不验“为什么崩”。
上一节的单元测试钻在模块内部,连私有函数都能测。这一节把视角翻到外面:集成测试站在用户位置,只用公开 API 验证整个库;文档测试让写给读者看的示例代码自动跑起来。
学习目标
读完本节,你会:在 tests/ 写集成测试并理解它为何只能用公开 API;用 tests/common/mod.rs 共享辅助;处理二进制 crate 测不了的问题;写文档测试,含隐藏行与 should_panic、compile_fail、no_run 标记;判断一个检查该放哪一层。
核心概念
集成测试:黑盒验证对外承诺
集成测试把库当黑盒:不关心内部实现,只验证公开 API 的行为是否符合承诺——几个公开函数串起来的用户流程对不对、边界与错误路径是否如文档所说。单元测试问“零件对不对”,集成测试问“组装起来用起来对不对”。
集成测试放在项目根的 tests/ 目录,每个 .rs 文件是一个独立测试 crate:
1
2
3
4
5
6
7
| my-crate/
├── Cargo.toml
├── src/lib.rs
└── tests/
├── slug.rs # 一个集成测试 crate
├── cart.rs # 另一个
└── common/mod.rs # 共享辅助(不是测试 crate)
|
1
2
3
4
5
6
7
8
| // tests/slug.rs:像外部用户一样 use 你的库
use textkit::{is_valid_slug, slugify};
#[test]
fn slugify_basic() {
assert_eq!(slugify("Hello Rust World"), "hello-rust-world");
assert!(is_valid_slug("hello-rust"));
}
|
关键事实:
- 只能用公开 API。集成测试是独立 crate,通过
use 你的crate::... 引入库,私有项不在其视野内,写了直接编译失败。这正是黑盒的强制力:你只能测用户能测的东西。 - 不需要
#[cfg(test)]。tests/ 代码只在 cargo test 时编译,文件本身就是 crate 根,不用写 mod tests。 - 运行:
cargo test 跑全部;cargo test --test slug 只跑 tests/slug.rs;输出里每个集成文件有独立的 Running tests/slug.rs 段落。 - dev-dependencies:测试专用辅助 crate 写在
Cargo.toml 的 [dev-dependencies],不进发布产物。
共享辅助:tests/common/mod.rs
多个集成文件共用搭建代码(样本数据、临时环境)时,标准做法是 tests/common/mod.rs,各文件 mod common; 后 use common::...。必须用子目录的 mod.rs 而不是 tests/common.rs:tests/ 下每个 .rs 文件都会被当成独立测试 crate 编译,common.rs 没有测试也会被白编译一份、多一段空输出;子目录里的文件不会被当成测试目标。
二进制 crate:先把逻辑抽到 lib
只有 src/main.rs 的二进制 crate 不能被集成测试 import——没有可供 use 的库目标。标准解法:逻辑抽到 src/lib.rs,main.rs 只做解析参数、调库函数、打印结果的薄层。集成测试测库;二进制本身可用 std::process::Command 真启动进程测,路径用 env!("CARGO_BIN_EXE_<二进制名>") 编译期注入。“集成测试写不下去”多半就是逻辑全在 main.rs。
文档测试:文档里的代码自动跑
/// 文档注释里的代码块,cargo test 会抽出来编译运行,这叫文档测试。它防文档腐烂:API 改了、示例没改,文档测试立刻变红。文档里能看到的代码,一定是能跑的代码。
1
2
3
4
5
6
7
8
9
10
| /// 把摄氏温度换算成华氏温度。
///
/// # 示例
///
/// ```
/// assert_eq!(textkit::celsius_to_fahrenheit(100.0), 212.0);
/// ```
pub fn celsius_to_fahrenheit(c: f64) -> f64 {
c * 9.0 / 5.0 + 32.0
}
|
要点:文档测试只对库 crate 的公开项生效,cargo test --doc 单独跑这一类;代码块默认被包进 fn main() 编译,自己写了 fn main 或 use 也能处理;以 # 开头的隐藏行参与编译但不显示在文档页面上,适合放 use 与搭建样板,让展示的示例保持干净;失败时报错会指出是哪个函数的哪段示例。
文档测试标记:should_panic、compile_fail、no_run
代码块语言后加标记,改变“通过”的定义:
```should_panic:代码必须 panic 才算通过,演示“这样调用会崩”的契约。```compile_fail:代码必须编译失败才算通过,钉住“这种写法不允许”(传错类型、借用不允许等)。它只验“编不过”、不验失败原因,别拿它钉报错文案。```no_run:只编译不运行,适合需要文件、网络的示例——保证 API 用法正确,不真的执行。```ignore:完全跳过。尽量少用:被 ignore 的示例等于没有保证,API 改了也不会变红。
标记可组合,如 ```rust,no_run;无标记就是编译并运行。
三种测试怎么分工
- 单元测试:贴着实现测零件,含私有函数与边界细节,快而多。
- 集成测试:用户视角测公开 API 与多步流程,验证组装后的承诺。
- 文档测试:测写给读者的示例,保证文档不说谎,每个公开 API 至少一个。
判断一个检查放哪层,看它依赖什么:需要私有可见性放单元;只用公开 API 且验证跨函数流程放集成;本身就是文档示例就当文档测试。关键承诺在集成层有意冗余一遍是好事:内部重构时单元测试跟着改、集成测试不动,行为漂移立刻现形。
可运行代码
沙箱是单文件程序,没有 tests/ 与文档测试运行器;下面把同样的检查放进 main 执行,真实项目里按注释搬到对应位置。
示例 1:黑盒集成测试(只用公开 API)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| // 示例 1:集成测试视角——站在外部用户的位置,只用公开 API 检查行为
mod textkit {
// 私有辅助函数:集成测试看不见它,只能通过公开函数的行为间接验证
fn normalize_char(c: char) -> Option<char> {
match c {
'a'..='z' | '0'..='9' => Some(c),
'A'..='Z' => Some(c.to_ascii_lowercase()),
' ' | '-' | '_' => Some('-'),
_ => None,
}
}
/// 把标题转成 URL slug:小写、空格变连字符、去掉其他符号、合并连续连字符。
pub fn slugify(title: &str) -> String {
let mut out = String::new();
for c in title.chars() {
if let Some(n) = normalize_char(c) {
if n == '-' && (out.is_empty() || out.ends_with('-')) {
continue;
}
out.push(n);
}
}
out.trim_end_matches('-').to_string()
}
/// 判断字符串是否已经是合法 slug。
pub fn is_valid_slug(s: &str) -> bool {
!s.is_empty() && slugify(s) == s
}
}
fn main() {
// 真实项目里这段代码放在 tests/slug.rs:use textkit::{slugify, is_valid_slug};
// 集成测试是独立 crate,只能用 pub 项,写 textkit::normalize_char 会直接编译失败
assert_eq!(textkit::slugify("Hello Rust World"), "hello-rust-world");
assert_eq!(textkit::slugify(" Rust 2024!! "), "rust-2024");
assert_eq!(textkit::slugify("a--b__c"), "a-b-c");
assert_eq!(textkit::slugify(""), "");
assert!(textkit::is_valid_slug("hello-rust"));
assert!(!textkit::is_valid_slug("Hello Rust"));
assert!(!textkit::is_valid_slug(""));
println!("slugify(\"Hello Rust World\") = {}", textkit::slugify("Hello Rust World"));
println!("slugify(\" Rust 2024!! \") = {}", textkit::slugify(" Rust 2024!! "));
println!("is_valid_slug(\"hello-rust\") = {}", textkit::is_valid_slug("hello-rust"));
println!("全部黑盒断言通过:集成测试不关心内部怎么实现,只钉住对外承诺的行为");
}
|
输出:
1
2
3
4
| slugify("Hello Rust World") = hello-rust-world
slugify(" Rust 2024!! ") = rust-2024
is_valid_slug("hello-rust") = true
全部黑盒断言通过:集成测试不关心内部怎么实现,只钉住对外承诺的行为
|
本地复现:cargo new textkit --lib,模块内容放 src/lib.rs,断言搬进 tests/slug.rs 改成 #[test] 函数,cargo test --test slug 运行;再故意调用一次私有函数,看编译错误——那就是黑盒边界。
示例 2:文档测试与隐藏行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| // 示例 2:文档测试——文档里的示例代码会被 cargo test 自动编译运行
/// 把摄氏温度换算成华氏温度。
///
/// # 示例
///
/// ```
/// # fn celsius_to_fahrenheit(c: f64) -> f64 { c * 9.0 / 5.0 + 32.0 }
/// assert_eq!(celsius_to_fahrenheit(100.0), 212.0);
/// assert_eq!(celsius_to_fahrenheit(0.0), 32.0);
/// ```
fn celsius_to_fahrenheit(c: f64) -> f64 {
c * 9.0 / 5.0 + 32.0
}
/// 返回两个数中较大的一个;相等时返回该值。
///
/// ```
/// # fn max_of(a: i32, b: i32) -> i32 { if a >= b { a } else { b } }
/// assert_eq!(max_of(3, 7), 7);
/// assert_eq!(max_of(5, 5), 5);
/// ```
fn max_of(a: i32, b: i32) -> i32 {
if a >= b { a } else { b }
}
fn main() {
// 沙箱按普通程序运行,不会执行文档注释里的代码块;
// 这里手动跑一遍与文档示例相同的断言,模拟 cargo test --doc 的检查
assert_eq!(celsius_to_fahrenheit(100.0), 212.0);
assert_eq!(celsius_to_fahrenheit(0.0), 32.0);
assert_eq!(max_of(3, 7), 7);
assert_eq!(max_of(5, 5), 5);
println!("celsius_to_fahrenheit(100.0) = {}", celsius_to_fahrenheit(100.0));
println!("max_of(3, 7) = {}", max_of(3, 7));
println!("文档示例断言全部通过(真实项目里 cargo test 会自动跑 /// 里的代码块)");
println!("以 # 开头的行是隐藏行:文档页面不显示,但参与编译,适合放样板代码");
}
|
输出:
1
2
3
4
| celsius_to_fahrenheit(100.0) = 212
max_of(3, 7) = 7
文档示例断言全部通过(真实项目里 cargo test 会自动跑 /// 里的代码块)
以 # 开头的行是隐藏行:文档页面不显示,但参与编译,适合放样板代码
|
隐藏行里放函数定义是沙箱单文件的写法;真实库里文档示例直接 use 本 crate 公开函数,隐藏行放 use 与搭建代码。本地把函数与注释放进 src/lib.rs 并设为 pub,cargo test --doc 应全绿;改错一个期望,看失败如何定位到具体函数的示例。
示例 3:端到端场景与共享辅助
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
| // 示例 3:端到端集成场景 + 共享辅助(真实项目里辅助放 tests/common/mod.rs)
mod shop {
#[derive(Debug, Clone)]
pub struct Item {
pub name: String,
pub price_cents: u32,
pub qty: u32,
}
#[derive(Debug, Default)]
pub struct Cart {
items: Vec<Item>,
}
impl Cart {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, name: &str, price_cents: u32, qty: u32) {
self.items.push(Item { name: name.to_string(), price_cents, qty });
}
pub fn subtotal_cents(&self) -> u32 {
self.items.iter().map(|i| i.price_cents * i.qty).sum()
}
/// 满 10000 分(100 元)包邮,否则运费 800 分;空车运费 0。
pub fn shipping_cents(&self) -> u32 {
let s = self.subtotal_cents();
if s == 0 || s >= 10_000 { 0 } else { 800 }
}
pub fn total_cents(&self) -> u32 {
self.subtotal_cents() + self.shipping_cents()
}
pub fn summary(&self) -> String {
self.items.iter().map(|i| format!("{}x{}", i.name, i.qty)).collect::<Vec<_>>().join(", ")
}
}
}
// 模拟 tests/common/mod.rs 里的共享辅助:每个集成测试文件都能 use common::sample_cart();
fn sample_cart() -> shop::Cart {
let mut c = shop::Cart::new();
c.add("Rust 教程", 6_000, 1);
c.add("贴纸", 500, 2);
c
}
fn main() {
// 场景 1:凑满包邮门槛的完整流程(加购 -> 小计 -> 运费 -> 总价)
let cart = sample_cart();
assert_eq!(cart.subtotal_cents(), 7_000);
assert_eq!(cart.shipping_cents(), 800);
assert_eq!(cart.total_cents(), 7_800);
println!("场景 1:{},小计 {} 分,运费 {} 分,总价 {} 分", cart.summary(), cart.subtotal_cents(), cart.shipping_cents(), cart.total_cents());
// 场景 2:再加一件越过门槛,运费变 0
let mut cart2 = sample_cart();
cart2.add("马克杯", 3_500, 1);
assert_eq!(cart2.subtotal_cents(), 10_500);
assert_eq!(cart2.shipping_cents(), 0);
assert_eq!(cart2.total_cents(), 10_500);
println!("场景 2:小计 {} 分,运费 {} 分,总价 {} 分(满 100 元包邮)", cart2.subtotal_cents(), cart2.shipping_cents(), cart2.total_cents());
// 场景 3:空车
let empty = shop::Cart::new();
assert_eq!(empty.total_cents(), 0);
println!("场景 3:空车总价 {} 分", empty.total_cents());
println!("集成测试的价值:几个公开 API 串起来的用户流程对不对,一眼看清");
}
|
输出:
1
2
3
4
| 场景 1:Rust 教程x1, 贴纸x2,小计 7000 分,运费 800 分,总价 7800 分
场景 2:小计 10500 分,运费 0 分,总价 10500 分(满 100 元包邮)
场景 3:空车总价 0 分
集成测试的价值:几个公开 API 串起来的用户流程对不对,一眼看清
|
sample_cart 就是 tests/common/mod.rs 里的共享辅助:各集成文件 mod common; 后共用一份样本搭建,规则改一处、所有场景同步。集成层命名宜用场景式(如 checkout_free_shipping_over_threshold),描述用户故事而非零件。
示例 4:文档测试标记 should_panic 与 compile_fail
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| // 示例 4:文档测试的三种标记——should_panic / compile_fail / no_run(用运行模拟前两种语义)
use std::panic;
/// 取切片的第一个元素;空切片会 panic。
///
/// ```should_panic
/// # fn first(xs: &[i32]) -> i32 { xs[0] }
/// first(&[]);
/// ```
fn first(xs: &[i32]) -> i32 {
xs[0]
}
/// 把字符串解析成端口号。
///
/// ```compile_fail
/// # fn parse_port(s: &str) -> u16 { s.parse().unwrap() }
/// let p: u16 = parse_port(8080); // 传了整数而不是 &str:故意写错,编译失败才算通过
/// ```
fn parse_port(s: &str) -> u16 {
s.parse().expect("端口必须是数字")
}
fn main() {
assert_eq!(first(&[10, 20]), 10);
assert_eq!(parse_port("8080"), 8080);
println!("first(&[10, 20]) = {}", first(&[10, 20]));
println!("parse_port(\"8080\") = {}", parse_port("8080"));
// should_panic 的语义:代码必须 panic 才算通过
let r = panic::catch_unwind(|| first(&[]));
match r {
Err(_) => println!("should_panic 模拟通过:first(&[]) 确实 panic 了"),
Ok(v) => println!("should_panic 模拟失败:本应 panic 却得到 {v}"),
}
// compile_fail 的语义:代码必须编译失败才算通过(沙箱无法演示编译失败,这里只说明)
println!("compile_fail:文档里故意写错的代码若能编译通过,测试反而失败");
println!("no_run:只编译不运行,适合需要文件/网络的示例;ignore:完全跳过,尽量少用");
println!("标记写在代码块语言后:```should_panic / ```compile_fail / ```no_run");
}
|
输出(标准输出;should_panic 模拟的 panic 信息走标准错误):
1
2
3
4
5
6
| first(&[10, 20]) = 10
parse_port("8080") = 8080
should_panic 模拟通过:first(&[]) 确实 panic 了
compile_fail:文档里故意写错的代码若能编译通过,测试反而失败
no_run:只编译不运行,适合需要文件/网络的示例;ignore:完全跳过,尽量少用
标记写在代码块语言后:```should_panic / ```compile_fail / ```no_run
|
compile_fail 在沙箱里无法演示(沙箱只运行能编译的程序),但语义要记清:它把“这段代码不该能编译”变成可执行断言;哪天 API 改得让错误写法合法,文档测试变红,提醒你反例已失效。
常见坑
- 在集成测试里测私有项。独立 crate 看不见私有项;测私有逻辑放单元测试,别为测试把内部函数改成
pub。 - 纯二进制 crate 写集成测试。没有
lib.rs 就没有可 import 的目标,先抽库。 - 共享辅助写成
tests/common.rs。会被当成独立测试 crate 白编译一份;正确位置是 tests/common/mod.rs。 - 文档示例用 ignore 逃避。永远不变红等于放弃保证;能编译用
no_run,能跑就不加标记。 - compile_fail 钉报错文案。它只验“编不过”,不验原因。
- 文档示例依赖外部环境。读真实文件、连网络在 CI 里必挂;改内存数据或用
no_run。 - 集成测试复制单元测试。逐函数复刻内部检查只会让两边一起改;集成层钉流程与承诺。
- 忘记 dev-dependencies。测试专用 crate 写进普通
[dependencies] 会进发布产物。 - 文档测试只写 happy path。错误路径也是承诺,
should_panic 与错误返回的示例都该有。
动手练习
本地完成(只用标准库):
cargo new textkit --lib,在 src/lib.rs 实现示例 1 的 slugify 与 is_valid_slug,给 slugify 写带断言示例的 /// 文档。建 tests/slug.rs 写至少三个集成测试:基本转换、连续分隔符与首尾空白、空字符串;建 tests/common/mod.rs 放样本标题辅助,集成测试里 mod common; 后表驱动。- 跑
cargo test,确认输出同时有 Running tests/slug.rs 与 Doc-tests 段落;再用 cargo test --test slug 与 cargo test --doc 各单独跑一遍。 - 给文档加一个
compile_fail 示例(传整数给 slugify),确认通过;改成合法调用看它变红,再改回。最后在集成测试里故意调用私有辅助函数,记录编译错误,改回。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| // tests/slug.rs 骨架(补全断言)
mod common;
use textkit::{is_valid_slug, slugify};
#[test]
fn slugify_cases() {
for (input, want) in common::sample_titles() {
assert_eq!(slugify(input), want, "输入 {input:?}");
}
assert!(is_valid_slug("hello-rust"));
assert!(!is_valid_slug(""));
}
// tests/common/mod.rs
pub fn sample_titles() -> Vec<(&'static str, &'static str)> {
vec![("Hello Rust World", "hello-rust-world"), ("a--b__c", "a-b-c"), ("", "")]
}
|
思考题:
- 集成测试里
use textkit::normalize_char;(私有函数),编译错误会说什么?为什么这个错误本身就是集成测试价值的一部分? - 文档示例需要读配置文件才能跑:用
no_run、ignore、还是改内存数据?三者保证强度有何差别? - 重构后单元测试全绿、集成测试红了一个。更可能是重构改坏了行为,还是集成测试写错了?为什么集成层能抓到单元层抓不到的问题?
小结与预告
核心就四句话:集成测试是独立 crate 里的黑盒检查,只用公开 API 验证对外承诺与多步用户流程,放在 tests/、共享辅助放 tests/common/mod.rs,纯二进制项目先把逻辑抽到 lib.rs;文档测试让 /// 里的示例被 cargo test 自动编译运行,隐藏行藏样板、should_panic 钉崩溃契约、compile_fail 钉“不许这样写”、no_run 只验编译;分工上单元测零件(含私有)、集成测组装后的承诺、文档测写给读者的示例,关键承诺在集成层有意冗余,重构漂移立刻现形;一条 cargo test 全跑,--test <文件名> 与 --doc 可单独跑。
下一节 15.3:文档注释与 cargo doc。这一节跑的是 /// 里的代码,下一节讲怎么写好注释、生成并发布 API 文档。
配套练习:在学习站动手练这一节
本文代码基于 Rust 1.8x / Edition 2024 验证。