Rust 最佳实践
Clippy lint、rustfmt 格式化、常见惯用法、性能 Profile
Rust 最佳实践
Rust 的工具链极其友好——cliipy 检查代码质量、rustfmt 统一格式、cargo 生态完善。
学完本章你将: 掌握 Clippy、rustfmt、常见惯用法、性能 Profile。
Clippy —— 代码检查
bash
rustup component add clippy
cargo clippy # 运行 lint 检查
# 建议采纳
cargo clippy --fix # 自动修复部分问题
rust
// Clippy 会警告的问题示例:
let v = vec![1, 2, 3];
if v.len() == 0 { } // ⚠️ 建议用 v.is_empty()
if x == true { } // ⚠️ 建议直接 if x
rustfmt —— 格式化
bash
rustup component add rustfmt
cargo fmt # 格式化整个项目
cargo fmt -- --check # 检查但不修改
常见惯用法
rust
// ✅ 用 iter() 而不是 for + 下标
let sum: i32 = nums.iter().sum();
// ✅ 用 match 而不是多重 if
match x { 0 => ..., _ => ... }
// ✅ 用 ? 传播错误
let data = fs::read_to_string("file.txt")?;
// ✅ 用 unwrap_or_else 提供懒求值默认
config.unwrap_or_else(|| default_config())
// ✅ 用 as_deref() 处理 Option<&String> → Option<&str>
opt_string.as_deref()
性能分析
bash
# 基准测试
cargo bench
# flamegraph 火焰图
cargo install flamegraph
cargo flamegraph
# 编译优化
# Cargo.toml
[profile.release]
lto = true # 链接时优化
codegen-units = 1 # 更好的优化(编译更慢)
opt-level = 3