Rust 系统编程入门

知识库
知识库文档
/tech-stacks/rust/tutorial/Rust 系统编程入门.md

文档

Rust 系统编程入门教程

第一章:Rust 为什么与众不同

1.1 内存安全的三种路线对比

语言 策略 代价
C/C++ 手动管理 悬垂指针、内存泄漏、UB
Java/Go/Python GC 自动回收 运行时开销、暂停
Rust 编译期所有权+借用检查 无运行时开销,但学习曲线陡

1.2 所有权三大规则

  1. Rust 中每个值都有一个被称为**所有者(owner)**的变量
  2. 同一时间值有且仅有一个所有者
  3. 当所有者离开作用域,值被自动释放(drop 函数调用)

第二章:Cargo 项目结构

my-project/
├── Cargo.toml       # 依赖+元信息(类似 package.json)
├── Cargo.lock       # 精确依赖版本
├── src/
│   ├── main.rs      # 入口点(可执行文件)
│   └── lib.rs       # 库根
└── tests/           # 集成测试

常用命令:

cargo new my-app         # 创建项目
cargo build              # 编译
cargo build --release    # 优化编译
cargo run                # 编译+运行
cargo test               # 测试
cargo fmt                # 格式化代码
cargo clippy             # Lint 检查

第三章:核心类型

3.1 Option——没有 null

enum Option<T> {
    Some(T),
    None,
}

3.2 Result——强制错误处理

enum Result<T, E> {
    Ok(T),
    Err(E),
}

? 运算符:let f = File::open("a.txt")?; 等价于「Ok 则解包,Err 则早期返回」。

3.3 Vec 和 HashMap

let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);

let mut scores = HashMap::new();
scores.insert("Blue", 10);

第四章:Trait 系统

Trait 定义共享行为:

trait Summary {
    fn summarize(&self) -> String;
}

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{} - by {}", self.title, self.author)
    }
}

泛型约束:

fn notify<T: Summary>(item: &T) { ... }
// 或语法糖
fn notify(item: &impl Summary) { ... }

第五章:并发模型

Rust 的并发哲学:无畏并发(Fearless Concurrency)

  • Send trait:该类型可以安全地在线程间转移所有权
  • Sync trait:该类型可以通过引用在线程间共享
  • 数据竞争在编译期被检测
use std::thread;

let handle = thread::spawn(|| {
    println!("来自子线程");
});
handle.join().unwrap();

思考题

  1. 为什么 Rust 可以有「无 GC 的内存安全」?所有权系统与 GC 的根本区别是什么?
  2. String&str 的区别?什么时候用哪个?
  3. 什么是「生命周期省略规则」?编译器如何自动推断引用生命周期?
  4. Rust 的 trait 和 Java 的 interface 有什么本质不同?

信息

路径
/tech-stacks/rust/tutorial/Rust 系统编程入门.md
更新时间
2026/5/31