Rust 简介
系统介绍 Rust 起源与演进、六大设计目标、所有权/模式匹配/Option与Result/零成本抽象/无畏并发/Cargo、生态应用、基础语法速览以及 Axum/WalkDir 实战模式。
学完这一章,你能够
- 系统介绍 Rust 起源与演进、六大设计目标、所有权/模式匹配/Option与Result/零成本抽象/无畏并发/Cargo、生态应用、基础语法速览以及 Axum/WalkDir 实战模式。
起源背景、设计哲学与演进历程
Rust 最初诞生于 2006 年,由时任 Mozilla 工程师 Graydon Hoare 发起,2009 年获得 Mozilla Research 正式赞助组建团队开发。其核心初衷是直面 C/C++ 在系统编程中长期难以根除的两类痛点:空指针、悬垂指针与缓冲区溢出等内存安全隐患,以及数据竞争和死锁等并发难题。Rust 坚持“在编译期消灭 bug”的哲学,以强类型与所有权机制把检查前移至编译阶段;社区吉祥物是一只名为 Ferris 的螃蟹,象征友好与包容的技术文化。
从 2006 年个人实验到进入 Linux 6.1+ 内核,Rust 经历了近二十年的持续演进。2021 年由 AWS、Google、华为、微软与 Mozilla 联合成立 Rust 基金会,为语言的长期中立治理奠定了基础。发布策略上,Rust 保持每 6 周推出一个稳定版本的节奏,并大约每 3 年通过 Edition(如 2018、2021、2024;注:Rust 2024 Edition 实际随 Rust 1.85.0 于 2025 年 2 月正式稳定)引入需要语法过渡的演进特性,同时保证同一工程内不同 Edition 的 crate 无缝混编、向后兼容。
核心语言特性拆解
围绕安全、高效与实用三个维度,所有权系统(Ownership)是 Rust 最具辨识度的机制:编译器在无需 GC 或手工 `malloc`/`free` 的前提下静态管理内存,遵循“单所有者、出作用域自动 `drop`、读写借用互斥”三条铁律。当堆分配的 `String` 从 `s1` 赋值给 `s2` 时所有权发生移动(move),原变量 `s1` 随即失效;而 `i32` 等栈上 `Copy` 类型赋值则直接复制。虽然初学者常感学习曲线偏陡,但被编译器挡下的正是 C/C++ 中最隐蔽的运行时灾难。本站离线脚本已模拟验证 `String` 移动失效、`i32` 复制以及多重不可变引用与独占可变引用的互斥逻辑。
模式匹配(`match`)要求编译器进行穷尽性检查,支持闭区间范围匹配(如 `90..=100`、`60..=89`)、通配符 `_` 及元组解构。与之相配合,Rust 的枚举(`enum`)可携带任意类型载荷:标准库内置 `Option<T>`(`Some`/`None`)取代空指针 `null`,用 `Result<T, E>`(`Ok`/`Err`)取代隐式 `try-catch` 异常,配合 `match` 或 `if let` 在编译期强制处理空值与错误分支。离线脚本验证了分数分级、`Vec::get` 越界返回 `None` 以及虚拟读取缺失文件返回 `Err`。
零成本抽象(Zero-Cost Abstractions)意味着迭代器链(`.iter().filter().map().collect()`)、闭包与泛型在编译优化后会展开为与手写底层循环等价的机器码,离线脚本对 `1..=10` 偶数的平方链式求值精确得到 `[4, 16, 36, 64, 100]`。在并发方面,编译器借助 `Send` 与 `Sync` 自动标记类型能否跨线程传递或共享,配合 `Arc<Mutex<T>>` 在编译期拦截非线程安全共享;离线脚本通过 10 个线程加互斥锁累加核验最终计数精确为 `10`。
在工程体验上,官方构建系统与包管理器 Cargo 将依赖拉取、编译、测试、文档、格式化与发布整合为一体,告别了传统 C/C++ 手工拼接多套构建脚本的割裂感。日常开发中 `cargo check` 只执行语法与类型检查而不生成最终二进制文件,速度显著快于 `cargo build`,是编辑器保存时实时诊断的核心命令。
主流应用领域与快速起步
凭借内存安全与贴近硬件的性能,Rust 在多条技术赛道迅速成熟:高性能服务端常采用异步运行时 Tokio 与 Actix Web、Axum 等 Web 框架;WebAssembly 领域以体积小、无 GC 见长,催生了 Yew、Leptos 等前端框架并被 Figma、Cloudflare Workers 等在生产环境使用;嵌入式与 IoT 场景则可通过 `no_std` 模式直接运行于无操作系统裸机,配合 RTIC 或 Embassy 框架开发微控制器固件。
在命令行工具方面,Rust 单文件零依赖分发孕育了 `ripgrep`、`fd`、`bat`、`delta`、`zoxide`、`dust` 等一批高频效率工具;区块链与 Web3 领域涵盖 Solana、Sui、Aptos 及基于 Substrate 的 Polkadot 生态;数据基础设施中出现了 TiKV、SurrealDB、Polars 与 Databend;操作系统层面,Linux 6.1+ 已合入 Rust 支持,Android 与 Windows 也在关键底层组件引入 Rust,另有社区从零编写的 Redox OS。
起步阶段通常通过 `rustup` 一次性安装 `rustc`、`cargo` 与本地文档,再用 `cargo new hello_rust` 生成包含 `Cargo.toml`(项目元数据、Edition 与 `[dependencies]`)和 `src/main.rs` 的标准骨架,并执行 `cargo run` 编译运行。本站使用 Python 3.12 标准库 `tomllib` 真实解析了包含 `edition = "2024"` 及依赖声明的 `Cargo.toml`。
基础语法速览与工程实战示例
Rust 语法融合了系统语言控制力与函数式表达力。变量默认不可变,需要修改时显式添加 `mut`;常量用 `const` 声明且必须标注类型(惯例全大写);变量遮蔽(Shadowing)则是用新的 `let` 同名绑定覆盖旧变量,既可转换类型又保持不可变语义,与 `mut` 就地改值有本质区别。静态类型系统要求编译期确定全部类型(涵盖定宽整型、浮点、`bool`、4 字节 `char`、元组、栈数组、切片、`Vec<T>` 与 `String`/`&str`)。
控制流包含 `if`、`loop`、`while`、`for` 与 `match`,其中 `if` 与 `loop`(借助 `break value`)均可作为表达式返回值。函数通过 `fn` 定义并显式标注参数与返回类型,末尾不带分号的表达式自动作为返回值,可用元组返回多值并用 trait bound 约束泛型函数(如 `fn largest<T: PartialOrd>`)。数据结构使用 `struct` 定义,在 `impl` 块中组织关联函数(如 `User::new`)与接收 `&self`/`&mut self` 的实例方法。离线脚本已逐项核对上述遮蔽、控制流、多值函数与结构体方法结果。
在真实工程中,两类高频范式极具代表性:一是基于 `axum`、`tokio`、`serde` 与 `serde_json` 构建编译期校验路由和查询参数提取(`Query<HelloParams>`)的 JSON HTTP API 服务;二是基于 `walkdir` 与 `HashMap` 递归遍历目录、按文件扩展名聚合文件数/总行数/字节数并降序输出报表的 CLI 工具。离线脚本模拟验证了 `/hello` 带参与默认参数的 JSON 响应结构以及按扩展名聚合排序结果。
生态工具、常见误区与学习路线
除基础构建命令外,`rustup update`、`rustup component add rustfmt/clippy`、`rustup doc`、`cargo add`、`cargo tree`、`cargo bench` 与 `cargo install` 共同构成了日常效率工具箱。初学者常见的第一关是“与借用检查器磨合”,编译器拒绝代码本质是在提前拦截运行时隐患;第二关是区分拥有堆所有权、可修改的 `String` 与不可变字符串视图 `&str`(函数形参优先选用 `&str`,因为 `&String` 可自动解引用转换传入)。
错误处理上应严格区分不可恢复错误(`panic!`)与可恢复错误(`Result`,库代码优先返回 `Result` 由调用方决策)。`unsafe` 关键字用于裸指针和 FFI 等极少数场景,并非关闭所有检查,而是把局部安全不变式的证明责任交还给开发者。对于大型工程编译偏慢的问题,可通过 `cargo check`、拆分 workspace 子 crate、`sccache` 缓存以及更快存储与多核 CPU 显著缓解。
建议按以下路径循序渐进:先通读官方免费书籍《The Rust Programming Language》并攻克所有权章节,同时在 Rust Playground 即时试验;接着用 Rustlings 完成小练习、阅读 Rust by Example 熟悉地道写法;最后挑选一个熟悉的实用工具用 Rust 重写。综合来看,Rust 在系统编程、高性能后端、Wasm、嵌入式、区块链、CLI 与数据库领域优势突出,而在极速一次性原型或传统成熟 GUI 生态下需权衡编译与学习投入。
Rust 六大核心设计目标
| 设计目标 | 核心说明 |
| 内存安全(无 GC) | 借助编译期所有权与借用检查保障内存安全,无需运行时垃圾回收器。 |
| 零成本抽象 | 迭代器、闭包、泛型等高层抽象在编译优化后与手写底层循环开销相当。 |
| 无畏并发 | 通过类型系统与所有权规则在编译阶段拦截数据竞争。 |
| 实用性 | 既可胜任内核与嵌入式底层,也能高效编写 Web 服务与 CLI 工具。 |
| 强类型推断 | 编译器基于上下文自动推导绝大多数局部类型,减少冗余标注。 |
| 丰富的工具链 | 官方集成 Cargo、rustfmt 与 clippy,形成统一开箱即用的工程规范。 |
Rust 发展演进关键里程碑
| 时间 | 版本/事件 | 核心说明 |
| 2006 年 | 个人项目 | Graydon Hoare 发起 Rust 语言早期设计。 |
| 2009 年 | Mozilla 赞助 | Mozilla 正式投入赞助并组建专职开发团队。 |
| 2010 年 | 首次公开 | 在 Mozilla 峰会对外发布早期 OCaml 实现的编译器。 |
| 2011 年 | 自举完成 | rustc 编译器改由 Rust 自身编写,脱离 OCaml 依赖。 |
| 2015 年 5 月 | Rust 1.0 | 首个稳定版发布,正式确立向后兼容承诺与生产可用性。 |
| 2018 年 12 月 | Rust 2018 Edition | 首个 Edition 发布,落地非词法生命周期(NLL)与模块路径简化。 |
| 2019 年 | 异步生态成形 | async/await 语法稳定,Tokio 等异步运行时走向成熟。 |
| 2021 年 | Rust 基金会成立 | AWS、Google、华为、微软与 Mozilla 联合成立独立基金会。 |
| 2021 年 10 月 | Rust 2021 Edition | 引入闭包字段级精确捕获与数组 IntoIterator 等改进。 |
| 2022 年 | Linux 内核采用 | Linux 6.1 合并 Rust 基础设施,成为内核官方支持的第二语言。 |
| 2025 年 2 月(来源原标 2024 年 2 月,已勘误) | Rust 2024 Edition | 随 Rust 1.85.0 正式稳定,进一步统一语言一致性与工具体验。 |
Rust 所有权与借用三大规则
| 规则 | 说明 | 工程含义 |
| 每个值有且仅有一个所有者 | 任一时刻一个值只归属单个变量绑定。 | 消除二次释放(double-free)与悬垂指针风险。 |
| 所有者离开作用域,值被释放 | 变量退出作用域时编译器自动插入 drop 调用。 | 无需手动 malloc/free,亦无 GC 停顿。 |
| 同一时刻:要么一个可变引用,要么多个不可变引用 | 读写互斥、多读共存。 | 在编译阶段静态阻断数据竞争。 |
Cargo 常用命令速查
| 命令 | 功能 | 典型场景 |
| cargo new project | 初始化新工程 | 自动创建 Cargo.toml 与 src/main.rs 标准骨架。 |
| cargo build | 调试模式编译 | 日常本地开发构建未优化调试二进制。 |
| cargo build --release | 发布模式优化编译 | 生产部署前开启全部编译器优化。 |
| cargo run | 编译并运行 | 快速执行当前二进制目标并观察输出。 |
| cargo test | 执行测试套件 | 运行单元测试、集成测试与文档测试。 |
| cargo check | 快速静态检查 | 不生成机器码产物,用于 IDE 实时报错反馈。 |
| cargo doc --open | 生成并浏览文档 | 本地生成当前项目与依赖 crate 的 HTML 文档。 |
| cargo clippy | 静态代码检查 | 识别非地道写法、性能陷阱与潜在逻辑缺陷。 |
| cargo fmt | 统一代码排版 | 按官方 rustfmt 规则自动格式化源代码。 |
| cargo publish | 发布开源包 | 打包并上传 crate 至 crates.io 注册表。 |
Rust 代表性命令行效率工具
| 工具 | 核心功能 | 常见传统替代对象 |
| ripgrep (rg) | 极速正则递归文本搜索 | grep |
| fd | 人性化高速文件查找 | find |
| bat | 带语法高亮与 Git 标记的文件查看 | cat |
| delta | 语法高亮与并排视图的差异比较 | git diff |
| zoxide | 基于访问频率的智能目录跳转 | cd |
| dust | 直观树状磁盘占用分析 | du |
Rust 常用基础与复合数据类型
| 类别 | 类型 | 示例 | 说明 |
| 有符号整数 | i8, i16, i32, i64, i128, isize | let x: i32 = -42; | 默认整数字面量推导类型为 i32。 |
| 无符号整数 | u8, u16, u32, u64, u128, usize | let y: u64 = 100; | usize 随平台指针位宽变化,常用于下标和长度。 |
| 浮点数 | f32, f64 | let pi: f64 = 3.14; | 默认浮点推导类型为双精度 f64。 |
| 布尔值 | bool | let ok: bool = true; | 仅取 true 或 false。 |
| 字符 | char | let c = 'R'; | 固定 4 字节,表示单个 Unicode 标量值。 |
| 元组 | (T1, T2, ...) | let t: (i32, f64) = (10, 3.14); | 定长且各位置元素类型可不同。 |
| 数组 | [T; N] | let a: [i32; 3] = [1, 2, 3]; | 定长同类型集合,默认分配在栈上。 |
| 切片 | &[T] | let s: &[i32] = &a[..]; | 对数组或 Vec 连续区间的借用视图。 |
| 动态数组 | Vec<T> | let v: Vec<i32> = vec![1, 2, 3]; | 可动态伸缩,元素缓冲分配在堆上。 |
| 字符串 | String / &str | let s = String::from("hi"); | String 拥有可修改堆缓冲,&str 为只读切片引用。 |
Rust 生态进阶工具与命令速查
| 命令 | 功能 | 说明 |
| rustup update | 升级工具链 | 将本地 rustc、cargo 与标准库更新到最新稳定版。 |
| rustup component add rustfmt | 安装格式化组件 | 启用统一代码风格自动排版。 |
| rustup component add clippy | 安装静态检查组件 | 自动检测常见误用与可优化写法。 |
| rustup doc | 打开本地文档 | 离线查阅标准库 API 与官方文档。 |
| cargo add <crate> | 添加项目依赖 | 自动将依赖项及兼容版本写入 Cargo.toml。 |
| cargo update | 刷新依赖锁定 | 按 Cargo.toml 语义化约束更新 Cargo.lock。 |
| cargo tree | 检视依赖树 | 可视化展示直接与传递依赖图谱。 |
| cargo bench | 运行基准测试 | 量化对比关键路径代码吞吐与延迟。 |
| cargo install <tool> | 安装社区 CLI | 从 crates.io 编译安装 ripgrep 等二进制工具。 |
Rust 综合能力与选型评估
| 维度 | Rust 的实际表现 |
| 学习曲线 | 前期因所有权与生命周期较陡,但概念一致稳定,掌握后显著降低维护成本。 |
| 编译速度 | 因编译期静态分析与优化较多而偏慢,可结合 cargo check 与增量编译缓解。 |
| 运行时性能 | 无 GC 与零成本抽象使其达到与 C/C++ 同级的执行效率。 |
| 内存安全 | 在安全子集中于编译期消除空指针、悬垂指针与越界溢出。 |
| 并发安全 | 借助 Send/Sync 与借用规则在编译期杜绝数据竞争。 |
| 生态成熟度 | 在系统编程、WebAssembly、网络服务与区块链方向已高度成熟。 |
| 最适合 | 系统内核、高并发后端、Wasm、嵌入式、区块链、CLI 工具与存储数据库。 |
| 不太适合 | 追求极短构建周期的一次性原型,以及强依赖成熟商业 GUI 套件的桌面端场景。 |
离线验证 Rust 核心特性、Cargo.toml 解析、基础语法及 Axum/WalkDir 逻辑模型
展开查看收起
"""Offline Rust semantic verification lab for Chapter 02 (intro)."""
import json
import shutil
import threading
import tomllib
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def case_ownership_move_and_borrow():
heap = {"s1": "Hello, Rust!"}
# Move s1 -> s2
heap["s2"] = heap.pop("s1")
s1_moved = "s1" not in heap
# Copy i32
x = 42
y = x
# Multiple shared borrows
readers = [heap["s2"], heap["s2"]]
# Exclusive mutable borrow
data = ["rust"]
data.append("!")
mutated = "".join(data)
expected = {
"s1_invalidated": True,
"s2_value": "Hello, Rust!",
"copy_pair": [42, 42],
"shared_readers": ["Hello, Rust!", "Hello, Rust!"],
"mutated_value": "rust!",
}
actual = {
"s1_invalidated": s1_moved,
"s2_value": heap["s2"],
"copy_pair": [x, y],
"shared_readers": readers,
"mutated_value": mutated,
}
return {
"name": "ownership_move_and_borrow",
"summary": "模拟 String 移动失效、i32 复制、多重不可变借用与独占可变借用修改",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_pattern_matching_exhaustiveness():
def grade(score: int) -> str:
if 90 <= score <= 100:
return "A"
if 60 <= score <= 89:
return "B"
if 0 <= score <= 59:
return "C"
return "无效分数"
def describe_pair(pair: tuple[int, int]) -> str:
match pair:
case (0, y):
return f"first_zero:{y}"
case (x, 0):
return f"second_zero:{x}"
case (x, y):
return f"both:{x},{y}"
expected = {"score_85": "B", "score_105": "无效分数", "pair_3_7": "both:3,7", "pair_0_9": "first_zero:9"}
actual = {
"score_85": grade(85),
"score_105": grade(105),
"pair_3_7": describe_pair((3, 7)),
"pair_0_9": describe_pair((0, 9)),
}
return {
"name": "pattern_matching_exhaustiveness",
"summary": "验证 match 闭区间范围匹配、通配分支与元组解构模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_option_and_result_semantics():
numbers = [10, 20, 30]
def vec_get(vec, idx):
return ("Some", vec[idx]) if 0 <= idx < len(vec) else ("None", None)
def read_virtual_file(name: str, fs_map: dict[str, str]):
if name in fs_map:
return ("Ok", fs_map[name])
return ("Err", f"NotFound:{name}")
expected = {
"first": ["Some", 10],
"missing": ["None", None],
"missing_file": ["Err", "NotFound:config.txt"],
"present_file": ["Ok", "mode=release"],
}
actual = {
"first": list(vec_get(numbers, 0)),
"missing": list(vec_get(numbers, 5)),
"missing_file": list(read_virtual_file("config.txt", {"app.toml": "mode=release"})),
"present_file": list(read_virtual_file("app.toml", {"app.toml": "mode=release"})),
}
return {
"name": "option_and_result_semantics",
"summary": "验证 Option<T> 替代空指针与 Result<T, E> 替代异常的显式分支处理",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_zero_cost_iterator_pipeline():
data = list(range(1, 11))
result = [x * x for x in data if x % 2 == 0]
expected = [4, 16, 36, 64, 100]
return {
"name": "zero_cost_iterator_pipeline",
"summary": "验证 1..=10 链式 filter(偶数) + map(平方) + collect 的精确结果",
"expected": expected,
"actual": result,
"passed": result == expected,
}
def case_fearless_concurrency_arc_mutex():
lock = threading.Lock()
state = {"counter": 0}
def worker():
with lock:
state["counter"] += 1
threads = [threading.Thread(target=worker) for _ in range(10)]
for t in threads:
t.start()
for t in threads:
t.join()
expected = {"threads": 10, "final_count": 10}
actual = {"threads": len(threads), "final_count": state["counter"]}
return {
"name": "fearless_concurrency_arc_mutex",
"summary": "以多线程互斥锁模拟 Arc<Mutex<i32>> 10 线程累加,核验最终计数无数据竞争",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cargo_toml_and_project_layout():
toml_text = """
[package]
name = "hello_rust"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
walkdir = "2"
"""
parsed = tomllib.loads(toml_text)
expected = {
"name": "hello_rust",
"version": "0.1.0",
"edition": "2024",
"tokio_features": ["full"],
"dep_count": 5,
"rustc_installed": False,
}
actual = {
"name": parsed["package"]["name"],
"version": parsed["package"]["version"],
"edition": parsed["package"]["edition"],
"tokio_features": parsed["dependencies"]["tokio"]["features"],
"dep_count": len(parsed["dependencies"]),
"rustc_installed": shutil.which("rustc") is not None,
}
return {
"name": "cargo_toml_and_project_layout",
"summary": "使用 Python 3.12 tomllib 真实解析 Cargo.toml 元数据与异步/CLI 依赖项",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_syntax_control_fn_struct():
# Shadowing: 5 -> 6 -> 12
x = 5
x = x + 1
x = x * 2
# if expression + loop expression
score = 75
grade = "A" if score >= 90 else ("B" if score >= 60 else "C")
count = 0
while True:
count += 1
if count == 5:
loop_val = count * 2
break
# Functions
def divide(a: float, b: float):
return (0.0, "错误:除数不能为零") if b == 0.0 else (a / b, "OK")
# Struct User
user = {"name": "rustacean", "email": "dev@example.com", "active": True, "login_count": 0}
user["login_count"] += 1
user["login_count"] += 1
# String &str coercion
s = "Hello" + ", world!"
expected = {
"shadowed_x": 12,
"grade": "B",
"loop_val": 10,
"add_10_20": 30,
"divide_ok": [5.0, "OK"],
"divide_zero": [0.0, "错误:除数不能为零"],
"largest": 9,
"login_count": 2,
"greet_from_string": "你好,Hello, world!!",
}
actual = {
"shadowed_x": x,
"grade": grade,
"loop_val": loop_val,
"add_10_20": 10 + 20,
"divide_ok": list(divide(10.0, 2.0)),
"divide_zero": list(divide(10.0, 0.0)),
"largest": max([3, 7, 2, 9, 5]),
"login_count": user["login_count"],
"greet_from_string": f"你好,{s}!",
}
return {
"name": "syntax_control_fn_struct",
"summary": "验证变量遮蔽、if/loop 表达式、多返回元组函数、泛型最大值与结构体方法逻辑",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cli_axum_and_walkdir_simulation():
def axum_hello(name: str | None):
target = name if name is not None else "Guest"
return {
"code": 200,
"message": f"你好,{target}!欢迎访问 Rust HTTP 服务",
"data": {"name": target},
}
# Simulated directory files for extension stats
files = [
("src/main.rs", 40, 1200),
("src/lib.rs", 25, 800),
("Cargo.toml", 15, 420),
("README", 8, 210),
]
stats: dict[str, list[int]] = {}
for path, lines, size in files:
ext = path.rsplit(".", 1)[1].lower() if "." in path else "(无扩展名)"
cur = stats.setdefault(ext, [0, 0, 0])
cur[0] += 1
cur[1] += lines
cur[2] += size
ordered = sorted(stats.items(), key=lambda kv: (-kv[1][0], kv[0]))
expected = {
"api_with_name": {"code": 200, "message": "你好,Rust开发者!欢迎访问 Rust HTTP 服务", "data": {"name": "Rust开发者"}},
"api_default": {"code": 200, "message": "你好,Guest!欢迎访问 Rust HTTP 服务", "data": {"name": "Guest"}},
"walkdir_summary": [["rs", [2, 65, 2000]], ["(无扩展名)", [1, 8, 210]], ["toml", [1, 15, 420]]],
}
actual = {
"api_with_name": axum_hello("Rust开发者"),
"api_default": axum_hello(None),
"walkdir_summary": [[k, v] for k, v in ordered],
}
return {
"name": "cli_axum_and_walkdir_simulation",
"summary": "模拟 Axum GET /hello JSON 响应与 WalkDir 按扩展名聚合统计排序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ownership_move_and_borrow(),
case_pattern_matching_exhaustiveness(),
case_option_and_result_semantics(),
case_zero_cost_iterator_pipeline(),
case_fearless_concurrency_arc_mutex(),
case_cargo_toml_and_project_layout(),
case_syntax_control_fn_struct(),
case_cli_axum_and_walkdir_simulation(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
因为 &str 既可以直接接受字符串字面量,又能通过 Deref 自动解引用接受 &String,避免强制调用方在堆上额外克隆或转移所有权。