Rust 工程实践
这一页偏“可落地”:项目结构、依赖管理、测试、错误处理和性能排查。
一、推荐项目结构
text
my-rust-app/
├─ Cargo.toml
├─ src/
│ ├─ main.rs
│ ├─ lib.rs
│ ├─ config.rs
│ ├─ error.rs
│ └─ service/
│ └─ user.rs
└─ tests/
└─ api_test.rsmain.rs 通常作为程序入口,lib.rs 承载可复用模块与对外导出,tests/ 用于放置集成测试,三者分工清晰后项目会更容易维护。
二、Cargo 常用命令
bash
cargo new my-rust-app
cargo check
cargo run
cargo test
cargo clippy -- -D warnings
cargo fmt --allcargo check 反馈速度快,适合高频开发循环。clippy 与 fmt 建议直接接入 CI,用来保证代码风格和质量的一致性。
三、依赖管理建议
在 Cargo.toml 中区分运行时依赖和开发依赖:
toml
[dependencies]
serde = { version = "1", features = ["derive"] }
anyhow = "1"
[dev-dependencies]
pretty_assertions = "1"依赖版本建议锁定在稳定主版本范围内,避免无感破坏更新;关键依赖升级时,要同步补上回归测试,防止功能退化。
四、错误处理策略
实践里可按两层处理错误:应用边界层使用 anyhow::Result 聚合上下文,库或领域层使用 thiserror 定义明确、可匹配的错误类型。
rust
use anyhow::{Context, Result};
use std::fs;
fn read_config(path: &str) -> Result<String> {
let text = fs::read_to_string(path)
.with_context(|| format!("failed to read config: {path}"))?;
Ok(text)
}五、测试分层
测试体系建议由浅到深分三层:模块内单元测试验证函数逻辑,tests/ 下的集成测试验证模块协同,端到端测试验证完整链路(接口、数据库、配置)。
rust
#[cfg(test)]
mod tests {
fn add(a: i32, b: i32) -> i32 { a + b }
#[test]
fn test_add() {
assert_eq!(add(1, 2), 3);
}
}六、性能与可观测性
性能分析常用 criterion 做基准测试,tracing 与 tracing-subscriber 做链路追踪,cargo flamegraph 做 CPU/内存热点分析(按平台配置)。
建议先通过指标定位瓶颈,再做针对性优化,避免“感觉式调优”。
七、Web 后端栈推荐
一套常见后端栈是 axum + tokio + sqlx(or sea-orm) + serde,配置层再配合 config 和环境变量管理。这个组合足够覆盖大多数中小型服务场景。
适合从“一个可运行 API 服务”开始,逐步引入鉴权、缓存、消息队列等能力。