Rust for C# Programmers: Complete Training Guide
Rust 面向 C# 程序员:完整训练指南
A comprehensive guide to learning Rust for developers with C# experience. This guide covers everything from basic syntax to advanced patterns, focusing on the conceptual shifts and practical differences between the two languages.
这是一本面向 C# 开发者的 Rust 完整训练指南,内容从基础语法一直覆盖到高级模式,重点讲清两门语言在思维方式和工程实践上的关键差异。
Course Overview
课程总览
- The case for Rust — Why Rust matters for C# developers: performance, safety, and correctness
为什么要学 Rust:对 C# 开发者来说,Rust 的价值主要体现在性能、安全性和正确性。 - Getting started — Installation, tooling, and your first program
快速开始:安装、工具链和第一个程序。 - Basic building blocks — Types, variables, control flow
基础构件:类型、变量和控制流。 - Data structures — Arrays, tuples, structs, collections
数据结构:数组、元组、结构体和集合。 - Pattern matching and enums — Algebraic data types and exhaustive matching
模式匹配与枚举:代数数据类型与穷尽匹配。 - Ownership and borrowing — Rust’s memory management model
所有权与借用:Rust 的内存管理模型。 - Modules and crates — Code organization and dependencies
模块与 crate:代码组织方式与依赖管理。 - Error handling — Result-based error propagation
错误处理:基于 Result 的错误传播方式。 - Traits and generics — Rust’s type system
Trait 与泛型:Rust 类型系统的核心能力。 - Closures and iterators — Functional programming patterns
闭包与迭代器:函数式编程常用模式。 - Concurrency — Fearless concurrency with type-system guarantees, async/await deep dive
并发:在类型系统保证下的 fearless concurrency,以及 async/await 深入解析。 - Unsafe Rust and FFI — When and how to go beyond safe Rust
Unsafe Rust 与 FFI:何时以及如何越过安全 Rust 的边界。 - Migration patterns — Real-world C# to Rust patterns and incremental adoption
迁移模式:真实世界里的 C# → Rust 转换模式和渐进式引入方式。 - Best practices — Idiomatic Rust for C# developers
最佳实践:适合 C# 开发者掌握的 Rust 惯用写法。
Self-Study Guide
自学指南
This material works both as an instructor-led course and for self-study. If you’re working through it on your own, here’s how to get the most out of it.
这套材料既适合讲师带读,也适合个人自学。如果是自己推进,下面这套节奏最容易把效果吃满。
Pacing recommendations:
学习节奏建议:
| Chapters | Topic | Suggested Time | Checkpoint |
|---|---|---|---|
| 1–4 第 1–4 章 | Setup, types, control flow 环境准备、类型与控制流 | 1 day 1 天 | You can write a CLI temperature converter in Rust 能够用 Rust 写一个命令行温度转换器。 |
| 5–6 第 5–6 章 | Data structures, enums, pattern matching 数据结构、枚举与模式匹配 | 1–2 days 1–2 天 | You can define an enum with data and match exhaustively on it能够定义带数据的枚举,并用 match 做穷尽匹配。 |
| 7 第 7 章 | Ownership and borrowing 所有权与借用 | 1–2 days 1–2 天 | You can explain why let s2 = s1 invalidates s1能够讲清 为什么 let s2 = s1 会让 s1 失效。 |
| 8–9 第 8–9 章 | Modules, error handling 模块与错误处理 | 1 day 1 天 | You can create a multi-file project that propagates errors with ?能够建立一个多文件项目,并用 ? 传播错误。 |
| 10–12 第 10–12 章 | Traits, generics, closures, iterators Trait、泛型、闭包与迭代器 | 1–2 days 1–2 天 | You can translate a LINQ chain to Rust iterators 能够把一串 LINQ 操作翻译成 Rust 迭代器链。 |
| 13 第 13 章 | Concurrency and async 并发与 async | 1 day 1 天 | You can write a thread-safe counter with Arc<Mutex<T>>能够用 Arc<Mutex<T>> 写出线程安全计数器。 |
| 14 第 14 章 | Unsafe Rust, FFI, testing Unsafe Rust、FFI 与测试 | 1 day 1 天 | You can call a Rust function from C# via P/Invoke 能够通过 P/Invoke 从 C# 调用 Rust 函数。 |
| 15–16 第 15–16 章 | Migration, best practices, tooling 迁移、最佳实践与工具链 | At your own pace 按个人节奏 | Reference material — consult as you write real code 属于参考型内容,写真实项目时反复查阅即可。 |
| 17 第 17 章 | Capstone project 综合项目 | 1–2 days 1–2 天 | You have a working CLI tool that fetches weather data 完成一个可以获取天气数据的 CLI 工具。 |
How to use the exercises:
练习怎么做:
- Chapters include hands-on exercises in collapsible
<details>blocks with solutions
每章都带有可折叠的<details>实战练习块,并附有参考答案。 - Always try the exercise before expanding the solution. Struggling with the borrow checker is part of learning — the compiler’s error messages are your teacher
一定先自己做,再展开答案。 和借用检查器缠斗本来就是学习过程的一部分,编译器的报错就是老师。 - If you’re stuck for more than 15 minutes, expand the solution, study it, then close it and try again from scratch
如果卡住超过 15 分钟,就先展开答案研究,再关掉答案从头重做一遍。 - The Rust Playground lets you run code without a local install
Rust Playground 可以在没有本地环境的情况下直接运行代码。
Difficulty indicators:
难度标记:
- 🟢 Beginner — Direct translation from C# concepts
🟢 初级:很多内容都能从 C# 经验直接迁移过来。 - 🟡 Intermediate — Requires understanding ownership or traits
🟡 中级:需要真正理解所有权或 trait。 - 🔴 Advanced — Lifetimes, async internals, or unsafe code
🔴 高级:涉及生命周期、async 内部机制或 unsafe 代码。
When you hit a wall:
当读到卡住时:
- Read the compiler error message carefully — Rust’s errors are exceptionally helpful
仔细看编译器报错,Rust 的错误信息通常特别有帮助。 - Re-read the relevant section; concepts like ownership (ch7) often click on the second pass
回头重读相关章节,像所有权这种概念,很多时候第二遍才会真正开窍。 - The Rust standard library docs are excellent — search for any type or method
Rust 标准库文档 质量很高,类型和方法问题都值得直接去查。 - For deeper async patterns, see the companion Async Rust Training
如果想继续深挖 async,可以配合阅读姊妹教材 Async Rust Training。
Table of Contents
目录总览
Part I — Foundations
第一部分:基础
1. Introduction and Motivation 🟢
1. 引言与动机 🟢
- The Case for Rust for C# Developers
Rust 为什么值得 C# 开发者学习 - Common C# Pain Points That Rust Addresses
Rust 解决哪些 C# 常见痛点 - When to Choose Rust Over C#
什么时候该选 Rust,而不是 C# - Language Philosophy Comparison
语言哲学对比 - Quick Reference: Rust vs C#
Rust 与 C# 快速对照
2. Getting Started 🟢
2. 快速开始 🟢
- Installation and Setup
安装与环境配置 - Your First Rust Program
第一个 Rust 程序 - Cargo vs NuGet/MSBuild
Cargo 与 NuGet / MSBuild 对比 - Reading Input and CLI Arguments
读取输入与命令行参数 - Essential Rust Keywords (optional reference — consult as needed)
Rust 关键字速查表(可选参考)
3. Built-in Types and Variables 🟢
3. 内置类型与变量 🟢
- Variables and Mutability
变量与可变性 - Primitive Types Comparison
基本类型对照 - String Types: String vs &str
字符串类型:String 与 &str - Printing and String Formatting
打印与字符串格式化 - Type Casting and Conversions
类型转换 - True Immutability vs Record Illusions
真正的不可变性与 record 幻觉
4. Control Flow 🟢
4. 控制流 🟢
- Functions vs Methods
函数与方法 - Expression vs Statement (Important!)
表达式与语句的差异 - Conditional Statements
条件语句 - Loops and Iteration
循环与迭代
5. Data Structures and Collections 🟢
5. 数据结构与集合 🟢
- Tuples and Destructuring
元组与解构 - Arrays and Slices
数组与切片 - Structs vs Classes
Struct 与 Class - Constructor Patterns
构造器模式 Vec<T>vsList<T>Vec<T>与List<T>- HashMap vs Dictionary
HashMap 与 Dictionary
6. Enums and Pattern Matching 🟡
6. 枚举与模式匹配 🟡
- Algebraic Data Types vs C# Unions
代数数据类型与 C# 联合类型 - Exhaustive Pattern Matching
穷尽模式匹配 Option<T>for Null Safety
用Option<T>处理空安全- Guards and Advanced Patterns
guard 与进阶模式
7. Ownership and Borrowing 🟡
7. 所有权与借用 🟡
- Understanding Ownership
理解所有权 - Move Semantics vs Reference Semantics
移动语义与引用语义 - Borrowing and References
借用与引用 - Memory Safety Deep Dive
内存安全深入解析 - Lifetimes Deep Dive 🔴
生命周期深入解析 🔴 - Smart Pointers, Drop, and Deref 🔴
智能指针、Drop 与 Deref 🔴
8. Crates and Modules 🟢
8. crate 与模块 🟢
- Rust Modules vs C# Namespaces
Rust 模块与 C# 命名空间 - Crates vs .NET Assemblies
crate 与 .NET 程序集 - Package Management: Cargo vs NuGet
包管理:Cargo 与 NuGet
9. Error Handling 🟡
9. 错误处理 🟡
- Exceptions vs
Result<T, E>
异常与Result<T, E> - The ? Operator
?运算符 - Custom Error Types
自定义错误类型 - Crate-Level Error Types and Result Aliases
crate 级错误类型与 Result 别名 - Error Recovery Patterns
错误恢复模式
10. Traits and Generics 🟡
10. Trait 与泛型 🟡
- Traits vs Interfaces
Trait 与接口 - Inheritance vs Composition
继承与组合 - Generic Constraints: where vs trait bounds
泛型约束:where 与 trait bound - Common Standard Library Traits
标准库常见 Trait
11. From and Into Traits 🟡
11. From 与 Into Trait 🟡
- Type Conversions in Rust
Rust 中的类型转换 - Implementing From for Custom Types
为自定义类型实现 From
12. Closures and Iterators 🟡
12. 闭包与迭代器 🟡
- Rust Closures
Rust 闭包 - LINQ vs Rust Iterators
LINQ 与 Rust 迭代器 - Macros Primer
宏入门
Part II — Concurrency & Systems
第二部分:并发与系统
13. Concurrency 🔴
13. 并发 🔴
- Thread Safety: Convention vs Type System Guarantees
线程安全:约定式与类型系统保证式 - async/await: C# Task vs Rust Future
async/await:C# Task 与 Rust Future - Cancellation Patterns
取消模式 - Pin and tokio::spawn
Pin 与 tokio::spawn
14. Unsafe Rust, FFI, and Testing 🟡
14. Unsafe Rust、FFI 与测试 🟡
- When and Why to Use Unsafe
何时以及为何使用 Unsafe - Interop with C# via FFI
通过 FFI 与 C# 互操作 - Testing in Rust vs C#
Rust 与 C# 的测试方式对比 - Property Testing and Mocking
性质测试与 Mocking
Part III — Migration & Best Practices
第三部分:迁移与最佳实践
15. Migration Patterns and Case Studies 🟡
15. 迁移模式与案例研究 🟡
- Common C# Patterns in Rust
C# 常见模式在 Rust 中的改写 - Essential Crates for C# Developers
C# 开发者必备 crate - Incremental Adoption Strategy
渐进式引入策略
16. Best Practices and Reference 🟡
16. 最佳实践与参考 🟡
- Idiomatic Rust for C# Developers
适合 C# 开发者掌握的 Rust 惯用法 - Performance Comparison: Managed vs Native
托管与原生性能对比 - Common Pitfalls and Solutions
常见陷阱与解决方案 - Learning Path and Resources
学习路径与资源 - Rust Tooling Ecosystem
Rust 工具生态
Capstone
综合项目
17. Capstone Project 🟡
17. 综合项目 🟡
- Build a CLI Weather Tool — combines structs, traits, error handling, async, modules, serde, and testing into a working application
构建一个命令行天气工具,把结构体、trait、错误处理、async、模块、serde 和测试串成一个可运行应用。