Rust Patterns & Engineering How-Tos
Rust 模式与工程技巧
Speaker Intro
讲者简介
- Principal Firmware Architect in Microsoft SCHIE (Silicon and Cloud Hardware Infrastructure Engineering) team
微软 SCHIE 团队首席固件架构师,SCHIE 即 Silicon and Cloud Hardware Infrastructure Engineering。 - Industry veteran with expertise in security, systems programming (firmware, operating systems, hypervisors), CPU and platform architecture, and C++ systems
长期从事安全、系统编程、固件、操作系统、虚拟机监控器、CPU 与平台架构,以及 C++ 系统开发。 - Started programming in Rust in 2017 (@AWS EC2), and have been in love with the language ever since
自 2017 年在 AWS EC2 接触 Rust 以来,就一直深度投入这门语言。
A practical guide to intermediate-and-above Rust patterns that arise in real codebases. This is not a language tutorial — it assumes you can write basic Rust and want to level up. Each chapter isolates one concept, explains when and why to use it, and provides compilable examples with inline exercises.
这是一本面向真实代码库的 Rust 进阶模式指南。它不是语法入门教程,默认已经具备基础 Rust 编写能力,目标是继续往上走。每章聚焦一个概念,讲清楚何时该用、为什么要用,并配上可编译示例和内嵌练习。
Who This Is For
适合哪些读者
- Developers who have finished The Rust Programming Language but struggle with “how do I actually design this?”
已经读完 The Rust Programming Language,但一落到实际设计就发懵的开发者。 - C++/C# engineers translating production systems into Rust
正在把生产系统从 C++ 或 C# 迁移到 Rust 的工程师。 - Anyone who has hit a wall with generics, trait bounds, or lifetime errors and wants a systematic toolkit
被泛型、trait bound 或生命周期错误卡过,想要一套系统方法论的人。
Prerequisites
前置知识
Before starting, you should be comfortable with:
开始之前,最好已经掌握以下基础:
- Ownership, borrowing, and lifetimes (basic level)
所有权、借用与生命周期的基础概念。 - Enums, pattern matching, and
Option/Result
枚举、模式匹配,以及Option/Result。 - Structs, methods, and basic traits (
Display,Debug,Clone)
结构体、方法,以及基础 trait,例如Display、Debug、Clone。 - Cargo basics:
cargo build,cargo test,cargo run
Cargo 基础命令:cargo build、cargo test、cargo run。
How to Use This Book
如何使用本书
Difficulty Legend
难度标记
Each chapter is tagged with a difficulty level:
每一章都会标上难度等级:
| Symbol | Level | Meaning |
|---|---|---|
| 🟢 🟢 | Fundamentals 基础 | Core concepts every Rust developer needs 每个 Rust 开发者都该掌握的核心概念。 |
| 🟡 🟡 | Intermediate 进阶 | Patterns used in production codebases 生产代码里经常用到的模式。 |
| 🔴 🔴 | Advanced 高级 | Deep language mechanics — revisit as needed 更深入的语言机制,按需反复查阅。 |
Pacing Guide
学习节奏建议
| Chapters | Topic | Suggested Time | Checkpoint |
|---|---|---|---|
| Part I: Type-Level Patterns 第一部分:类型层模式 | |||
| 1. Generics 🟢 1. 泛型 🟢 | Monomorphization, const generics, const fn单态化、const generics、 const fn | 1–2 hours 1–2 小时 | Can explain when dyn Trait beats generics能够说明什么时候 dyn Trait 比泛型更合适。 |
| 2. Traits 🟡 2. Trait 🟡 | Associated types, GATs, blanket impls, vtables 关联类型、GAT、blanket impl、虚表 | 3–4 hours 3–4 小时 | Can design a trait with associated types 能够设计带关联类型的 trait。 |
| 3. Newtype & Type-State 🟡 3. Newtype 与 Type-State 🟡 | Zero-cost safety, compile-time FSMs 零成本安全、编译期有限状态机 | 2–3 hours 2–3 小时 | Can build a type-state builder pattern 能够写出 type-state builder 模式。 |
| 4. PhantomData 🔴 4. PhantomData 🔴 | Lifetime branding, variance, drop check 生命周期标记、变型、drop check | 2–3 hours 2–3 小时 | Can explain why PhantomData<fn(T)> differs from PhantomData<T>能够说明为什么 PhantomData<fn(T)> 和 PhantomData<T> 不一样。 |
| Part II: Concurrency & Runtime 第二部分:并发与运行时 | |||
| 5. Channels 🟢 5. Channel 🟢 | mpsc, crossbeam, select!, actorsmpsc、crossbeam、select!、actor | 1–2 hours 1–2 小时 | Can implement a channel-based worker pool 能够实现基于 channel 的 worker pool。 |
| 6. Concurrency 🟡 6. 并发 🟡 | Threads, rayon, Mutex, RwLock, atomics 线程、rayon、Mutex、RwLock、原子类型 | 2–3 hours 2–3 小时 | Can pick the right sync primitive for a scenario 能够为具体场景选对同步原语。 |
| 7. Closures 🟢 7. 闭包 🟢 | Fn/FnMut/FnOnce, combinatorsFn / FnMut / FnOnce、组合器 | 1–2 hours 1–2 小时 | Can write a higher-order function that accepts closures 能够写出接受闭包的高阶函数。 |
| 8. Smart Pointers 🟡 8. 智能指针 🟡 | Box, Rc, Arc, RefCell, Cow, Pin Box、Rc、Arc、RefCell、Cow、Pin | 2–3 hours 2–3 小时 | Can explain when to use each smart pointer 能够说明各种智能指针的适用时机。 |
| Part III: Systems & Production 第三部分:系统与生产实践 | |||
| 9. Error Handling 🟢 9. 错误处理 🟢 | thiserror, anyhow, ? operatorthiserror、anyhow、 ? 运算符 | 1–2 hours 1–2 小时 | Can design an error type hierarchy 能够设计错误类型层次结构。 |
| 10. Serialization 🟡 10. 序列化 🟡 | serde, zero-copy, binary data serde、零拷贝、二进制数据 | 2–3 hours 2–3 小时 | Can write a custom serde deserializer 能够写出自定义 serde 反序列化器。 |
| 11. Unsafe 🔴 11. Unsafe 🔴 | Superpowers, FFI, UB pitfalls, allocators 五大超能力、FFI、UB 陷阱、分配器 | 2–3 hours 2–3 小时 | Can wrap unsafe code in a sound safe API 能够把 unsafe 代码包装成健全的安全 API。 |
| 12. Macros 🟡 12. 宏 🟡 | macro_rules!, proc macros, syn/quotemacro_rules!、过程宏、syn / quote | 2–3 hours 2–3 小时 | Can write a declarative macro with tt munching能够写出使用 tt munching 的声明式宏。 |
| 13. Testing 🟢 13. 测试 🟢 | Unit/integration/doc tests, proptest, criterion 单元测试、集成测试、文档测试、proptest、criterion | 1–2 hours 1–2 小时 | Can set up property-based tests 能够搭建性质测试。 |
| 14. API Design 🟡 14. API 设计 🟡 | Module layout, ergonomic APIs, feature flags 模块布局、易用 API、feature flag | 2–3 hours 2–3 小时 | Can apply the “parse, don’t validate” pattern 能够应用“parse, don’t validate”模式。 |
| 15. Async 🔴 15. Async 🔴 | Futures, Tokio, common pitfalls Future、Tokio、常见陷阱 | 1–2 hours 1–2 小时 | Can identify async anti-patterns 能够识别 async 反模式。 |
| Appendices 附录 | |||
| Reference Card 参考卡片 | Quick-look trait bounds, lifetimes, patterns 快速查阅 trait bound、生命周期与模式 | As needed 按需查阅 | — — |
| Capstone Project 综合项目 | Type-safe task scheduler 类型安全的任务调度器 | 4–6 hours 4–6 小时 | Submit a working implementation 完成一个可运行实现。 |
Total estimated time: 30–45 hours for thorough study with exercises.
预计总学习时间:如果把练习认真做完,大约需要 30–45 小时。
Working Through Exercises
练习怎么做
Every chapter ends with a hands-on exercise. For maximum learning:
每章结尾都有动手练习。想把收益拉满,建议按下面这套方式来:
- Try it yourself first — spend at least 15 minutes before opening the solution
先自己做。 至少先花 15 分钟思考,再去看答案。 - Type the code — don’t copy-paste; typing builds muscle memory
亲手敲代码。 别复制粘贴,手敲才能形成肌肉记忆。 - Modify the solution — add a feature, change a constraint, break something on purpose
改造答案。 加功能、改约束、故意弄坏一部分,再自己修回来。 - Check cross-references — most exercises combine patterns from multiple chapters
顺着交叉引用看。 多数练习都把几章里的模式揉到了一起。
The capstone project (Appendix) ties together patterns from across the book into a single, production-quality system.
附录里的综合项目会把整本书里的模式串到一个完整的、接近生产质量的系统里。
Table of Contents
目录总览
Part I: Type-Level Patterns
第一部分:类型层模式
1. Generics — The Full Picture 🟢
1. 泛型全景图 🟢
Monomorphization, code bloat trade-offs, generics vs enums vs trait objects, const generics, const fn.
单态化、代码膨胀权衡、泛型与枚举及 trait object 的取舍、const generics、const fn。
2. Traits In Depth 🟡
2. Trait 深入解析 🟡
Associated types, GATs, blanket impls, marker traits, vtables, HRTBs, extension traits, enum dispatch.
关联类型、GAT、blanket impl、标记 trait、虚表、HRTB、扩展 trait、枚举分发。
3. The Newtype and Type-State Patterns 🟡
3. Newtype 与 Type-State 模式 🟡
Zero-cost type safety, compile-time state machines, builder patterns, config traits.
零成本类型安全、编译期状态机、builder 模式、配置 trait。
4. PhantomData — Types That Carry No Data 🔴
4. PhantomData:不携带数据的类型 🔴
Lifetime branding, unit-of-measure pattern, drop check, variance.
生命周期标记、物理量单位模式、drop check、变型。
Part II: Concurrency & Runtime
第二部分:并发与运行时
5. Channels and Message Passing 🟢
5. Channel 与消息传递 🟢
std::sync::mpsc, crossbeam, select!, backpressure, actor pattern.std::sync::mpsc、crossbeam、select!、背压、actor 模式。
6. Concurrency vs Parallelism vs Threads 🟡
6. 并发、并行与线程 🟡
OS threads, scoped threads, rayon, Mutex/RwLock/Atomics, Condvar, OnceLock, lock-free patterns.
操作系统线程、作用域线程、rayon、Mutex / RwLock / 原子类型、Condvar、OnceLock、无锁模式。
7. Closures and Higher-Order Functions 🟢
7. 闭包与高阶函数 🟢
Fn/FnMut/FnOnce, closures as parameters/return values, combinators, higher-order APIs.Fn / FnMut / FnOnce、闭包作为参数和返回值、组合器、高阶 API。
9. Smart Pointers and Interior Mutability 🟡
9. 智能指针与内部可变性 🟡
Box, Rc, Arc, Weak, Cell/RefCell, Cow, Pin, ManuallyDrop.
Box、Rc、Arc、Weak、Cell / RefCell、Cow、Pin、ManuallyDrop。
Part III: Systems & Production
第三部分:系统与生产实践
10. Error Handling Patterns 🟢
10. 错误处理模式 🟢
thiserror vs anyhow, #[from], .context(), ? operator, panics.
thiserror 与 anyhow、#[from]、.context()、? 运算符、panic。
11. Serialization, Zero-Copy, and Binary Data 🟡
11. 序列化、零拷贝与二进制数据 🟡
serde fundamentals, enum representations, zero-copy deserialization, repr(C), bytes::Bytes.
serde 基础、枚举表示方式、零拷贝反序列化、repr(C)、bytes::Bytes。
12. Unsafe Rust — Controlled Danger 🔴
12. Unsafe Rust:受控的危险 🔴
Five superpowers, sound abstractions, FFI, UB pitfalls, arena/slab allocators.
五大超能力、健全抽象、FFI、UB 陷阱、arena / slab 分配器。
13. Macros — Code That Writes Code 🟡
13. 宏:会写代码的代码 🟡
macro_rules!, when (not) to use macros, proc macros, derive macros, syn/quote.macro_rules!、何时该用宏、何时别用宏、过程宏、派生宏、syn / quote。
14. Testing and Benchmarking Patterns 🟢
14. 测试与基准模式 🟢
Unit/integration/doc tests, proptest, criterion, mocking strategies.
单元测试、集成测试、文档测试、proptest、criterion、mock 策略。
15. Crate Architecture and API Design 🟡
15. Crate 架构与 API 设计 🟡
Module layout, API design checklist, ergonomic parameters, feature flags, workspaces.
模块布局、API 设计清单、易用参数设计、feature flag、workspace。
16. Async/Await Essentials 🔴
16. Async/Await 核心要点 🔴
Futures, Tokio quick-start, common pitfalls. (For deep async coverage, see our Async Rust Training.)
Future、Tokio 快速上手、常见陷阱。若想系统深挖 async,请继续看配套的 Async Rust Training。
Appendices
附录
Summary and Reference Card
总结与参考卡片
Pattern decision guide, trait bounds cheat sheet, lifetime elision rules, further reading.
模式选择指南、trait bound 速查、生命周期省略规则,以及延伸阅读。
Capstone Project: Type-Safe Task Scheduler
综合项目:类型安全任务调度器
Integrate generics, traits, typestate, channels, error handling, and testing into a complete system.
把泛型、trait、typestate、channel、错误处理与测试整合成一个完整系统。