Cargo 完全指南
Cargo 是 Rust 的包管理器和构建工具,类似于 npm (JavaScript)、pip (Python)、Maven (Java)。
目录
基本命令
项目创建
# 创建新项目(binary)
cargo new my-project
# 创建库项目(library)
cargo new my-lib --lib
# 在当前目录初始化
cargo init
构建与运行
# 编译项目(debug 模式)
cargo build
# 编译并运行
cargo run
# 编译优化版本(release 模式,速度快但编译慢)
cargo build --release
cargo run --release
# 只检查代码是否能编译(不生成二进制文件,速度快)
cargo check
依赖管理
# 添加依赖
cargo add serde
cargo add tokio --features full
# 更新依赖到最新兼容版本
cargo update
# 更新指定依赖
cargo update serde
# 查看依赖树
cargo tree
测试
# 运行所有测试
cargo test
# 运行指定测试
cargo test test_name
# 显示测试输出
cargo test -- --nocapture
# 运行文档测试
cargo test --doc
清理与文档
# 清理构建产物
cargo clean
# 生成并打开文档
cargo doc --open
# 格式化代码
cargo fmt
# 代码检查(lint)
cargo clippy
项目结构
my-project/
├── Cargo.toml # 项目配置文件(依赖、元数据)
├── Cargo.lock # 依赖版本锁定(自动生成,应提交到 git)
├── src/ # 源代码目录
│ ├── main.rs # binary crate 入口
│ ├── lib.rs # library crate 入口
│ └── bin/ # 多个可执行文件
│ └── another.rs
├── tests/ # 集成测试
│ └── integration_test.rs
├── benches/ # 性能基准测试
│ └── benchmark.rs
└── examples/ # 示例代码
└── example.rs
运行示例和测试
# 运行 examples/example.rs
cargo run --example example
# 运行 benches/benchmark.rs
cargo bench
# 运行 tests/integration_test.rs
cargo test --test integration_test
Cargo.toml 配置
基本结构
[package]
name = "user-service" # 项目名称
version = "0.1.0" # 版本号(遵循语义化版本)
edition = "2021" # Rust 版本(2015/2018/2021)
authors = ["Your Name <you@example.com>"]
description = "A user service"
license = "MIT"
repository = "https://github.com/user/repo"
[dependencies]
# 依赖项
[dev-dependencies]
# 开发/测试依赖
[build-dependencies]
# 构建脚本依赖
[features]
# 可选功能特性
本项目示例
[package]
name = "user-service"
version = "0.1.0"
edition = "2021"
[dependencies]
# Web 框架
axum = "0.6"
tokio = { version = "1", features = ["full"] }
# 数据库
sqlx = { version = "0.6", features = ["mysql", "runtime-tokio-native-tls", "chrono"] }
# 缓存
redis = { version = "0.21", features = ["tokio-comp", "connection-manager"] }
# 序列化
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# 日期时间
chrono = { version = "0.4", features = ["serde"] }
# 日志
tracing = "0.1"
tracing-subscriber = "0.3"
# 错误处理
anyhow = "1.0"
thiserror = "1.0"
# 环境变量
dotenv = "0.15"
依赖管理
版本指定
[dependencies]
# 精确版本
serde = "=1.0.150"
# 插入符号(默认):兼容更新
# ^1.2.3 = >=1.2.3, <2.0.0
serde = "^1.0"
serde = "1.0" # 同上
# 波浪号:补丁更新
# ~1.2.3 = >=1.2.3, <1.3.0
serde = "~1.0.150"
# 通配符
serde = "1.*"
# 范围
serde = ">=1.0, <2.0"
# 多个条件
serde = ">=1.30, <1.50"
依赖来源
[dependencies]
# crates.io(默认)
serde = "1.0"
# Git 仓库
my-lib = { git = "https://github.com/user/my-lib" }
my-lib = { git = "https://github.com/user/my-lib", branch = "main" }
my-lib = { git = "https://github.com/user/my-lib", tag = "v1.0" }
my-lib = { git = "https://github.com/user/my-lib", rev = "abc123" }
# 本地路径
my-lib = { path = "../my-lib" }
# 可选依赖
serde = { version = "1.0", optional = true }
Features(特性)
[dependencies]
# 启用特定 features
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.6", features = ["mysql", "runtime-tokio-native-tls"] }
# 禁用默认 features
serde = { version = "1.0", default-features = false }
# 定义自己的 features
[features]
default = ["json"]
json = ["serde", "serde_json"]
xml = ["serde", "quick-xml"]
# 启用 feature
cargo build --features json
cargo build --features "json xml"
cargo build --all-features
cargo build --no-default-features
构建与运行
构建配置
# 开发配置(cargo build)
[profile.dev]
opt-level = 0 # 优化级别 0-3
debug = true # 包含调试信息
overflow-checks = true # 整数溢出检查
# 发布配置(cargo build --release)
[profile.release]
opt-level = 3 # 最高优化
debug = false
lto = true # 链接时优化
codegen-units = 1 # 更好的优化(编译慢)
环境变量
# 指定编译目标
RUSTFLAGS="-C target-cpu=native" cargo build
# 并行编译任务数
cargo build -j 4
# 详细输出
cargo build -v
cargo build -vv
# 离线模式
cargo build --offline
测试
单元测试
// src/lib.rs 或任何源文件
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_addition() {
assert_eq!(2 + 2, 4);
}
#[test]
#[should_panic]
fn test_panic() {
panic!("Expected panic");
}
#[test]
#[ignore]
fn expensive_test() {
// 默认不运行,除非 cargo test -- --ignored
}
}
集成测试
// tests/integration_test.rs
use user_service::some_function;
#[test]
fn test_integration() {
assert!(some_function());
}
文档测试
/// 计算两个数之和
///
/// # Examples
///
/// ```
/// use my_crate::add;
/// assert_eq!(add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
测试命令
# 运行所有测试
cargo test
# 运行指定名称的测试
cargo test test_addition
# 运行指定模块的测试
cargo test tests::integration
# 显示 println! 输出
cargo test -- --nocapture
# 单线程运行
cargo test -- --test-threads=1
# 运行被 ignore 的测试
cargo test -- --ignored
# 运行所有测试(包括 ignored)
cargo test -- --include-ignored
发布
发布到 crates.io
# 登录 crates.io
cargo login <your-api-token>
# 打包检查
cargo package
# 本地测试打包结果
cargo package --list
# 发布(不可撤销!)
cargo publish
# 试运行(不实际发布)
cargo publish --dry-run
版本管理
遵循语义化版本 (Semantic Versioning):
MAJOR.MINOR.PATCH(例如:1.2.3)- MAJOR: 不兼容的 API 变更
- MINOR: 向后兼容的功能新增
- PATCH: 向后兼容的问题修复
# 更新版本号(手动修改 Cargo.toml)
# 然后提交 git tag
git tag v0.1.1
git push --tags
常用工具
cargo-edit
# 安装
cargo install cargo-edit
# 使用
cargo add serde
cargo rm serde
cargo upgrade
cargo-watch
# 安装
cargo install cargo-watch
# 文件变化时自动重新编译运行
cargo watch -x run
cargo watch -x test
cargo watch -x 'run --release'
cargo-expand
# 安装
cargo install cargo-expand
# 展开宏
cargo expand
cargo expand my_module
cargo-audit
# 安装
cargo install cargo-audit
# 检查依赖安全漏洞
cargo audit
cargo-outdated
# 安装
cargo install cargo-outdated
# 检查过期依赖
cargo outdated
cargo-tree
# 查看依赖树(内置)
cargo tree
# 查看特定依赖的反向依赖
cargo tree -i serde
工作区(Workspace)
多个 crate 的项目管理:
# 根目录 Cargo.toml
[workspace]
members = [
"crate1",
"crate2",
"crate3",
]
# 共享依赖版本
[workspace.dependencies]
serde = "1.0"
# 构建所有 crate
cargo build --workspace
# 运行特定 crate
cargo run -p crate1
# 测试所有 crate
cargo test --workspace
配置文件位置
全局配置
~/.cargo/config.toml
项目配置
.cargo/config.toml
示例配置
# .cargo/config.toml
# 使用国内镜像源
[source.crates-io]
replace-with = 'ustc'
[source.ustc]
registry = "https://mirrors.ustc.edu.cn/crates.io-index"
# 设置默认编译目标
[build]
target = "x86_64-unknown-linux-gnu"
# 并行编译数
jobs = 4
常见问题
1. 依赖冲突
# 更新 Cargo.lock
cargo update
# 清理重建
cargo clean
cargo build
2. 编译慢
# 使用 check 而不是 build
cargo check
# 减少优化
[profile.dev]
opt-level = 0
# 增量编译(默认已启用)
[build]
incremental = true
# 使用 sccache
cargo install sccache
export RUSTC_WRAPPER=sccache
3. 二进制文件在哪里
# Debug 模式
./target/debug/user-service
# Release 模式
./target/release/user-service
快速参考
| 命令 | 说明 |
|---|---|
cargo new <name> | 创建新项目 |
cargo build | 编译项目 |
cargo run | 编译并运行 |
cargo check | 快速检查编译 |
cargo test | 运行测试 |
cargo doc --open | 生成并打开文档 |
cargo clean | 清理构建产物 |
cargo update | 更新依赖 |
cargo tree | 查看依赖树 |
cargo fmt | 格式化代码 |
cargo clippy | 代码检查 |
cargo publish | 发布到 crates.io |
本项目常用命令
# 开发流程
cargo check # 快速检查
cargo build # 编译
cargo run # 运行服务
./test_api.sh # 测试 API(需要服务已运行)
# 发布流程
cargo build --release
./target/release/user-service