Rust 开发模式
构建安全、高性能且可维护应用程序的惯用 Rust 模式和最佳实践。
何时使用
- 编写新的 Rust 代码时
- 评审 Rust 代码时
- 重构现有 Rust 代码时
- 设计 crate 结构和模块布局时
工作原理
此技能在六个关键领域强制执行惯用的 Rust 约定:所有权和借用,用于在编译时防止数据竞争;Result/? 错误传播,库使用 thiserror 而应用程序使用 anyhow;枚举和穷尽模式匹配,使非法状态无法表示;用于零成本抽象的 trait 和泛型;通过 Arc<Mutex<T>>、通道和 async/await 实现的安全并发;以及按领域组织的最小化 pub 接口。
核心原则
1. 所有权和借用
Rust 的所有权系统在编译时防止数据竞争和内存错误。
// Good: Pass references when you don't need ownership
fn process(data: &[u8]) -> usize {
data.len()
}
// Good: Take ownership only when you need to store or consume
fn store(data: Vec<u8>) -> Record {
Record { payload: data }
}
// Bad: Cloning unnecessarily to avoid borrow checker
fn process_bad(data: &Vec<u8>) -> usize {
let cloned = data.clone(); // Wasteful — just borrow
cloned.len()
}
使用 Cow 实现灵活的所有权
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input) // Zero-cost when no mutation needed
}
}
错误处理
使用 Result 和 ? —— 切勿在生产环境中使用 unwrap()
// Good: Propagate errors with context
use anyhow::{Context,…