Cargo 最佳实践 #

概述 #

本节汇总了使用 Cargo 的最佳实践,帮助你更高效地管理 Rust 项目,提升代码质量和开发效率。

项目组织 #

目录结构 #

库项目 #

text
my_lib/
├── Cargo.toml
├── Cargo.lock
├── README.md
├── LICENSE
├── CHANGELOG.md
├── .gitignore
├── src/
│   ├── lib.rs           # 库入口
│   ├── module1.rs       # 模块
│   ├── module2/
│   │   ├── mod.rs
│   │   └── submodule.rs
│   └── utils.rs
├── tests/               # 集成测试
│   ├── integration.rs
│   └── common/
│       └── mod.rs
├── examples/            # 示例
│   ├── basic.rs
│   └── advanced.rs
├── benches/             # 性能测试
│   └── benchmark.rs
└── docs/                # 文档
    └── guide.md

应用项目 #

text
my_app/
├── Cargo.toml
├── Cargo.lock
├── README.md
├── .env                 # 环境变量
├── src/
│   ├── main.rs          # 程序入口
│   ├── lib.rs           # 库代码
│   ├── config.rs        # 配置
│   ├── handlers/        # 处理器
│   │   ├── mod.rs
│   │   └── user.rs
│   └── models/          # 数据模型
│       ├── mod.rs
│       └── user.rs
├── tests/
│   └── api_test.rs
├── config/              # 配置文件
│   ├── default.toml
│   └── production.toml
└── migrations/          # 数据库迁移
    └── 001_init.sql

工作区项目 #

text
my_workspace/
├── Cargo.toml           # 工作区配置
├── Cargo.lock           # 共享锁定文件
├── README.md
├── crates/              # 库包
│   ├── core/
│   ├── utils/
│   └── macros/
├── apps/                # 应用程序
│   ├── server/
│   └── cli/
├── examples/            # 示例
│   └── demo/
├── tests/               # 集成测试
│   └── e2e/
└── docs/                # 文档
    └── guide/

模块组织 #

rust
// src/lib.rs

// 公开 API
pub mod api;
pub mod client;
pub mod error;

// 内部模块
mod internal;
mod utils;

// 重导出常用类型
pub use api::{Config, Client};
pub use error::{Error, Result};

Cargo.toml 配置 #

完整配置模板 #

toml
[package]
name = "my_lib"
version = "0.1.0"
edition = "2021"
rust-version = "1.70"
description = "A brief description"
documentation = "https://docs.rs/my_lib"
homepage = "https://myproject.com"
repository = "https://github.com/user/my_lib"
license = "MIT OR Apache-2.0"
keywords = ["rust", "library"]
categories = ["development-tools"]
readme = "README.md"
authors = ["Author <author@example.com>"]
exclude = ["tests/*", "examples/*"]

[dependencies]
# 核心依赖
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", default-features = false, features = ["rt"] }

# 可选依赖
serde_json = { version = "1.0", optional = true }

[dev-dependencies]
tokio = { version = "1.0", features = ["full"] }
tempfile = "3.0"
pretty_assertions = "1.0"

[features]
default = ["std"]
std = []
json = ["dep:serde_json"]
full = ["std", "json"]

[profile.dev]
opt-level = 0
debug = true

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
strip = true

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

依赖管理最佳实践 #

toml
[dependencies]
# ✅ 推荐:指定版本范围
serde = "1.0"

# ✅ 推荐:只启用需要的特性
tokio = { version = "1.0", default-features = false, features = ["rt", "net"] }

# ✅ 推荐:大型依赖设为可选
serde_json = { version = "1.0", optional = true }

# ❌ 不推荐:使用通配符
# some-dep = "*"

# ❌ 不推荐:启用所有特性
# tokio = { version = "1.0", features = ["full"] }

依赖管理 #

版本约束策略 #

项目类型 版本约束策略
应用程序 精确版本或 Cargo.lock
库项目 兼容版本范围
内部包 工作区依赖

定期更新 #

bash
# 检查过时依赖
cargo install cargo-outdated
cargo outdated

# 更新依赖
cargo update

# 安全审计
cargo install cargo-audit
cargo audit

依赖审查 #

bash
# 查看依赖树
cargo tree

# 查看重复依赖
cargo tree --duplicates

# 查看依赖许可证
cargo install cargo-license
cargo license

# 查看依赖大小
cargo install cargo-bloat
cargo bloat --crates

性能优化 #

编译优化 #

Profile 配置 #

toml
[profile.dev]
opt-level = 0           # 开发时不优化
debug = true            # 包含调试信息
incremental = true      # 增量编译

[profile.release]
opt-level = 3           # 最高优化
lto = true              # 链接时优化
codegen-units = 1       # 单个代码生成单元
strip = true            # 移除符号信息

[profile.dev.package."*"]
opt-level = 2           # 依赖优化

开发时加速 #

toml
# 使用 check 代替 build
# cargo check 比 cargo build 快很多

[profile.dev]
# 开发时可以适度优化
opt-level = 1

运行时优化 #

减小二进制大小 #

toml
[profile.release]
opt-level = "z"         # 优化大小
lto = true
codegen-units = 1
strip = true
panic = "abort"         # 不展开栈

编译时优化 #

toml
[profile.release]
lto = "thin"            # Thin LTO,更快
codegen-units = 16      # 更多并行

缓存优化 #

yaml
# .github/workflows/ci.yml
- name: Cache cargo registry
  uses: actions/cache@v3
  with:
    path: |
      ~/.cargo/registry
      ~/.cargo/git
      target
    key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

测试最佳实践 #

测试组织 #

rust
#[cfg(test)]
mod tests {
    use super::*;

    mod unit_tests {
        use super::*;

        #[test]
        fn test_basic() {
            // 单元测试
        }
    }

    mod integration_tests {
        use super::*;

        #[test]
        fn test_integration() {
            // 集成测试
        }
    }
}

测试辅助函数 #

rust
#[cfg(test)]
mod test_utils {
    pub fn setup() -> TestContext {
        // 测试设置
        TestContext::new()
    }

    pub fn assert_approx_eq(a: f64, b: f64, epsilon: f64) {
        assert!((a - b).abs() < epsilon);
    }
}

CI 测试配置 #

yaml
# .github/workflows/test.yml
name: Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      
      - name: Check
        run: cargo check --all-targets
      
      - name: Test
        run: cargo test --workspace
      
      - name: Clippy
        run: cargo clippy --workspace -- -D warnings
      
      - name: Format
        run: cargo fmt --check
      
      - name: Doc
        run: cargo doc --workspace

文档最佳实践 #

文档注释 #

rust
/// Adds two numbers.
///
/// # Arguments
///
/// * `a` - The first number
/// * `b` - The second number
///
/// # Returns
///
/// The sum of `a` and `b`.
///
/// # Examples
///
/// ```
/// use my_lib::add;
///
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
///
/// # Panics
///
/// Panics if the result overflows.
///
/// # Errors
///
/// Returns an error if... (if applicable)
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

模块文档 #

rust
//! # My Library
//!
//! `my_lib` is a collection of utilities for...
//!
//! ## Features
//!
//! - Feature 1
//! - Feature 2
//!
//! ## Getting Started
//!
//! ```rust
//! use my_lib::function;
//!
//! function();
//! ```

README 模板 #

markdown
# my_lib

A brief description of what this library does.

## Installation

Add this to your `Cargo.toml`:

```toml
[dependencies]
my_lib = "0.1"

Usage #

rust
use my_lib::function;

fn main() {
    function();
}

Features #

  • feature1 - Description
  • feature2 - Description

Documentation #

License #

Licensed under either of Apache License, Version 2.0 or MIT license.

text

## 团队协作

### Git 配置

```gitignore
# .gitignore
/target/
/Cargo.lock  # 对于库项目

# IDE
/.idea/
/.vscode/
*.swp

# OS
.DS_Store
Thumbs.db

# Build
*.log

提交 Cargo.lock #

项目类型 是否提交 Cargo.lock
应用程序 ✅ 提交
库项目 ❌ 不提交
工作区 ✅ 提交到根目录

CI/CD 配置 #

yaml
# .github/workflows/ci.yml
name: CI

on: [push, pull_request]

jobs:
  ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy
      - uses: Swatinem/rust-cache@v2
      
      - name: Check format
        run: cargo fmt --check
      
      - name: Clippy
        run: cargo clippy --workspace --all-targets -- -D warnings
      
      - name: Test
        run: cargo test --workspace
      
      - name: Doc
        run: cargo doc --workspace --no-deps

代码审查清单 #

markdown
## 代码审查清单

### 代码质量
- [ ] 代码格式正确
- [ ] 无 clippy 警告
- [ ] 测试通过
- [ ] 文档完整

### 依赖管理
- [ ] 新依赖必要
- [ ] 版本约束合理
- [ ] Cargo.lock 更新

### 性能
- [ ] 无性能回退
- [ ] 编译时间合理
- [ ] 二进制大小合理

常见问题解决 #

1. 编译慢 #

bash
# 使用增量编译
CARGO_INCREMENTAL=1 cargo build

# 使用 sccache 缓存
cargo install sccache
export RUSTC_WRAPPER=sccache

# 减少并行任务
cargo build -j 2

2. 依赖冲突 #

bash
# 查看冲突
cargo tree --duplicates

# 使用 patch 解决
[patch.crates-io]
conflicting-dep = { path = "../fixed" }

3. 内存不足 #

bash
# 减少并行任务
cargo build -j 1

# 使用 32 位目标
cargo build --target i686-unknown-linux-gnu

4. 网络问题 #

toml
# 配置镜像源
[source.crates-io]
replace-with = 'rsproxy-sparse'

[source.rsproxy-sparse]
registry = "sparse+https://rsproxy.cn/index/"

工具推荐 #

开发工具 #

工具 用途
rust-analyzer IDE 支持
cargo-watch 自动重新编译
cargo-edit 依赖管理
cargo-outdated 检查过时依赖
cargo-audit 安全审计

质量工具 #

工具 用途
cargo-clippy 代码检查
cargo-fmt 代码格式化
cargo-tarpaulin 测试覆盖率
cargo-udeps 检查未使用依赖

发布工具 #

工具 用途
cargo-release 版本发布
cargo-workspaces 工作区管理
cargo-binstall 快速安装二进制

总结 #

遵循这些最佳实践可以帮助你:

  1. 提高开发效率:合理的项目组织和工具使用
  2. 保证代码质量:完善的测试和文档
  3. 优化性能:编译和运行时优化
  4. 团队协作:统一的规范和流程

继续探索 Cargo 的更多功能,不断提升你的 Rust 开发技能!

最后更新:2026-03-28