🚀 Cargo:Rust 生态系统的核心工具,让 Rust 项目管理变得简单高效。
包管理工具最重要的意义就是任何用户拿到你的代码,都能运行起来,而不会因为各种包版本依赖焦头烂额。
Cargo 是 Rust 的构建系统和包管理器,它是一个多功能工具,负责:
功能 | 描述 | 命令示例 |
|---|---|---|
🏗️ 项目创建 | 创建标准化的项目结构 | cargo new |
📦 依赖管理 | 下载、编译、管理第三方库 | cargo add |
🔨 代码构建 | 编译源代码为可执行文件 | cargo build |
🏃 程序运行 | 构建并运行程序 | cargo run |
🧪 测试执行 | 运行单元测试和集成测试 | cargo test |
📚 文档生成 | 生成项目和依赖文档 | cargo doc |
🚀 包发布 | 发布库到 crates.io | cargo publish |
Cargo 随 Rust 一起安装,无需单独安装:
# 安装 Rust(包含 Cargo)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 重新加载环境变量
source $HOME/.cargo/env
# 检查 Cargo 版本
cargo --version
# 输出示例:cargo 1.90.0 (840b83a10 2025-07-30)
# 检查 Rust 版本
rustc --version
# 输出示例:rustc 1.90.0 (1159e78c4 2025-09-14)
# 更新 Rust 和 Cargo 到最新版本
rustup update
# 创建新的可执行项目
cargo new my_project
cd my_project
# 或者在现有目录中初始化项目
mkdir existing_project
cd existing_project
cargo init
# 创建库项目(供其他项目依赖)
cargo new my_library --lib
my_project/
├── Cargo.toml # 📋 项目配置文件
├── Cargo.lock # 🔒 依赖锁定文件(自动生成)
├── src/ # 📁 源代码目录
│ └── main.rs # 🦀 主程序入口(二进制项目)
│ └── lib.rs # 📚 库入口(库项目)
├── tests/ # 🧪 集成测试目录
├── examples/ # 📝 示例代码目录
└── target/ # 🎯 构建输出目录
├── debug/ # 🐛 调试版本
└── release/ # 🚀 发布版本
# 构建调试版本(默认)
cargo build
# 构建发布版本(优化编译)
cargo build --release
模式 | 命令 | 优化程度 | 编译速度 | 运行速度 | 调试信息 | 使用场景 |
|---|---|---|---|---|---|---|
Debug | cargo build | ❌ | 🚀 快 | 🐌 慢 | ✅ 完整 | 开发调试 |
Release | cargo build --release | ✅ 高 | 🐌 慢 | 🚀 快 | ❌ 精简 | 生产发布 |
# 并行构建(利用多核 CPU)
cargo build -j 4
# 详细输出构建过程
cargo build --verbose
# 构建特定的 binary
cargo build --bin my_binary
# 构建并运行调试版本
cargo run
# 构建并运行发布版本
cargo run --release
# 运行特定的 binary
cargo run --bin my_binary
# 传递命令行参数
cargo run -- arg1 arg2 arg3
# 传递参数给发布版本
cargo run --release -- --config config.toml
cargo check 是开发过程中最常用的命令,它的优势:
# 快速检查代码
cargo check
# 检查所有目标(包括测试、示例等)
cargo check --all-targets
# 检查特定包
cargo check --package my_package
命令性能对比(大型项目):
cargo check ████░░░░░░ 30秒
cargo build ████████░░ 2分钟
cargo build --release ██████████ 5分钟
# 清理构建产物
cargo clean
# 清理特定目标
cargo clean --release
# 运行所有测试
cargo test
# 运行特定测试
cargo test test_name
# 显示测试输出
cargo test -- --nocapture
# 生成并打开文档
cargo doc --open
# 生成包含私有项的文档
cargo doc --document-private-items
文件 | 作用 | 编辑方式 | 版本控制 |
|---|---|---|---|
Cargo.toml | 📋 项目配置和依赖声明 | 👤 手动编辑 | ✅ 必须提交 |
Cargo.lock | 🔒 精确依赖版本锁定 | 🤖 自动生成 | 📦 看项目类型 |
# 应用程序项目 - 提交 Cargo.lock
my_app/
├── Cargo.toml
├── Cargo.lock ✅ 提交到 Git
└── src/
# 库项目 - 忽略 Cargo.lock
my_library/
├── Cargo.toml
├── Cargo.lock ❌ 添加到 .gitignore
└── src/
[package]
name = "my_project" # 项目名称
version = "0.1.0" # 版本号(遵循语义化版本)
edition = "2024" # Rust 版本(2018/2021/2024)
authors = ["Your Name <you@example.com>"]
description = "A sample Rust project"
license = "MIT OR Apache-2.0"
repository = "https://github.com/username/my_project"
homepage = "https://my_project.com"
documentation = "https://docs.rs/my_project"
readme = "README.md"
keywords = ["cli", "tool", "utility"]
categories = ["command-line-utilities"]
[package]
# 构建配置
build = "build.rs" # 构建脚本
exclude = ["tests/fixtures/*"] # 排除文件
include = ["src/**/*", "Cargo.toml"] # 包含文件
# 元数据
rust-version = "1.70" # 最低 Rust 版本要求
publish = false # 禁止发布到 crates.io
# 工作空间配置
workspace = true # 标记为工作空间成员
Cargo 支持多种依赖来源:
[dependencies]
# 1. crates.io 官方仓库(推荐)
serde = "1.0" # 最新兼容版本
tokio = "=1.25.0" # 精确版本
regex = "1.5.*" # 通配符版本
# 2. Git 仓库
my_crate = { git = "https://github.com/user/my_crate.git" }
my_crate = { git = "https://github.com/user/my_crate.git", branch = "main" }
my_crate = { git = "https://github.com/user/my_crate.git", tag = "v1.0.0" }
my_crate = { git = "https://github.com/user/my_crate.git", rev = "abc123" }
# 3. 本地路径
local_crate = { path = "../local_crate" }
workspace_crate = { path = "crates/workspace_crate" }
# 4. 带特性的依赖
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
reqwest = { version = "0.11", features = ["json", "rustls-tls"], default-features = false }
写法 | 含义 | 示例 | 匹配范围 |
|---|---|---|---|
"1.2.3" | 兼容版本 | "1.2.3" | >=1.2.3, <2.0.0 |
"=1.2.3" | 精确版本 | "=1.2.3" | 1.2.3 |
">=1.2.3" | 大于等于 | ">=1.2.3" | >=1.2.3 |
"~1.2.3" | 波浪号兼容 | "~1.2.3" | >=1.2.3, <1.3.0 |
"^1.2.3" | 插入符兼容 | "^1.2.3" | >=1.2.3, <2.0.0 |
"*" | 通配符 | "1.2.*" | >=1.2.0, <1.3.0 |
# 基础添加
cargo add serde # 添加最新版本
cargo add serde@1.0.136 # 添加特定版本
cargo add serde --features derive # 添加带特性的依赖
# 添加开发依赖
cargo add --dev criterion # 仅在测试/开发时使用
# 添加构建依赖
cargo add --build cc # 仅在构建时使用
# 添加可选依赖
cargo add serde --optional # 可选依赖,通过 features 启用
[dependencies]
# 运行时依赖
serde = "1.0"
tokio = "1.0"
[dev-dependencies]
# 开发和测试依赖(不会包含在最终发布包中)
criterion = "0.4"
proptest = "1.0"
[build-dependencies]
# 构建脚本依赖
cc = "1.0"
pkg-config = "0.3"
[target.'cfg(windows)'.dependencies]
# 平台特定依赖
winapi = "0.3"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
# 更新所有依赖到兼容的最新版本
cargo update
# 更新特定依赖
cargo update -p serde
# 查看可更新的依赖
cargo outdated # 需要安装 cargo-outdated
# 查看依赖树
cargo tree
# 查看重复依赖
cargo tree --duplicates
[features]
default = ["json"] # 默认启用的特性
json = ["serde/json"] # 特性定义
async = ["tokio"] # 依赖特定库的特性
full = ["json", "async"] # 组合特性
[dependencies]
serde = { version = "1.0", optional = true }
tokio = { version = "1.0", optional = true }
# 构建时指定特性
cargo build --features json
cargo build --features "json,async"
cargo build --all-features
cargo build --no-default-features
工作空间允许管理多个相关的包:
# 根目录的 Cargo.toml
[workspace]
members = [
"cli",
"core",
"utils",
]
resolver = "2"
[workspace.dependencies]
# 共享依赖版本
serde = "1.0"
tokio = "1.0"
# 工作空间命令
cargo build --workspace # 构建所有包
cargo test --workspace # 测试所有包
cargo build -p cli # 构建特定包
# .cargo/config.toml
[alias]
b = "build"
c = "check"
t = "test"
r = "run"
br = "build --release"
rr = "run --release"
[package]
name = "my_awesome_crate"
version = "0.1.0"
description = "An awesome Rust crate"
license = "MIT OR Apache-2.0"
repository = "https://github.com/username/my_awesome_crate"
documentation = "https://docs.rs/my_awesome_crate"
readme = "README.md"
keywords = ["awesome", "utility"]
categories = ["development-tools"]
# 1. 注册并登录 crates.io
cargo login your_api_token
# 2. 检查包内容
cargo package --list
# 3. 本地测试发布包
cargo package
cargo publish --dry-run
# 4. 正式发布
cargo publish
# 撤回版本(仅限72小时内)
cargo yank --vers 0.1.0
# 取消撤回
cargo yank --vers 0.1.0 --undo
# 查看发布的包
cargo search my_crate
// build.rs
use std::env;
fn main() {
// 设置环境变量
println!("cargo:rustc-env=BUILD_TIME={}", chrono::Utc::now());
// 条件编译
ifcfg!(target_os = "windows") {
println!("cargo:rustc-cfg=windows");
}
// 链接库
println!("cargo:rustc-link-lib=ssl");
// 重新构建条件
println!("cargo:rerun-if-changed=build.rs");
}
# Cargo.toml
[profile.dev]
opt-level = 0 # 无优化
debug = true # 包含调试信息
overflow-checks = true # 整数溢出检查
[profile.release]
opt-level = 3 # 最大优化
debug = false # 无调试信息
lto = true # 链接时优化
codegen-units = 1 # 单个代码生成单元
panic = "abort" # 崩溃时直接终止
[profile.bench]
opt-level = 3
debug = false
lto = true
让我们通过一个完整的项目来演示 Cargo 的使用:
# 创建项目
cargo new guess_number
cd guess_number
# 查看初始结构
tree
# guess_number/
# ├── Cargo.toml
# └── src/
# └── main.rs
# Cargo.toml
[package]
name = "guess_number"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
description = "A fun number guessing game"
license = "MIT"
[dependencies]
rand = "0.8.5"
colored = "2.0" # 彩色输出
# 使用 cargo add 命令
cargo add rand
cargo add colored
# 或手动编辑 Cargo.toml 后运行
cargo build
// src/main.rs
use std::io;
use std::cmp::Ordering;
use rand::Rng;
use colored::*;
fn main() {
println!("{}", "🎮 欢迎来到猜数字游戏!".bright_cyan().bold());
let secret_number = rand::thread_rng().gen_range(1..=100);
letmut attempts = 0;
loop {
println!("\n{}", "请输入你的猜测 (1-100):".yellow());
letmut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("无法读取输入");
let guess: u32 = match guess.trim().parse() {
Ok(num) if num >= 1 && num <= 100 => num,
Ok(_) => {
println!("{}", "请输入 1 到 100 之间的数字!".red());
continue;
}
Err(_) => {
println!("{}", "请输入一个有效的数字!".red());
continue;
}
};
attempts += 1;
println!("你猜的是:{}", guess.to_string().bright_white().bold());
match guess.cmp(&secret_number) {
Ordering::Less => println!("{}", "📈 太小了!".blue()),
Ordering::Greater => println!("{}", "📉 太大了!".blue()),
Ordering::Equal => {
println!("{}", format!("🎉 恭喜你,猜对了!用了 {} 次尝试", attempts).green().bold());
break;
}
}
}
}
# 快速检查代码
cargo check
# 运行调试版本
cargo run
# 运行发布版本(更快)
cargo run --release
// src/lib.rs
pubfn validate_guess(guess: u32) -> bool {
guess >= 1 && guess <= 100
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_guess() {
assert!(validate_guess(50));
assert!(validate_guess(1));
assert!(validate_guess(100));
assert!(!validate_guess(0));
assert!(!validate_guess(101));
}
}
# 运行测试
cargo test
# 运行测试并显示输出
cargo test -- --nocapture
my_project/
├── Cargo.toml # 项目配置
├── Cargo.lock # 依赖锁定(应用程序项目提交,库项目忽略)
├── README.md # 项目说明
├── LICENSE # 开源许可证
├── .gitignore # Git 忽略文件
├── src/
│ ├── main.rs # 二进制入口
│ ├── lib.rs # 库入口
│ └── modules/ # 模块目录
├── tests/ # 集成测试
├── examples/ # 示例代码
├── benches/ # 基准测试
└── docs/ # 额外文档
# 开发环境优化
[profile.dev]
opt-level = 1 # 轻度优化,平衡编译速度和运行速度
incremental = true # 增量编译
# 生产环境优化
[profile.release]
opt-level = 3 # 最大优化
lto = "fat" # 完整链接时优化
codegen-units = 1 # 单个代码生成单元
panic = "abort" # 崩溃时直接终止
strip = true # 移除调试符号
[dependencies]
# 优先使用语义版本
serde = "1.0" # ✅ 推荐
serde = "=1.0.136" # ❌ 过于严格
# 合理使用特性
tokio = { version = "1.0", features = ["rt-multi-thread", "net"] } # ✅ 只启用需要的特性
tokio = { version = "1.0", features = ["full"] } # ❌ 启用所有特性
# 安装有用的 Cargo 扩展
cargo install cargo-edit # cargo add/rm/upgrade 命令
cargo install cargo-watch # 文件变更时自动重新构建
cargo install cargo-outdated # 检查过时的依赖
cargo install cargo-audit # 安全审计
cargo install cargo-deny # 许可证和依赖检查
通过这个完整的指南,你应该已经掌握了 Cargo 的核心功能和高级用法。Cargo 还有更多强大的功能等待探索:
💡 提示:Cargo 不仅是一个工具,更是 Rust 生态系统的核心。掌握 Cargo 将让你的 Rust 开发之旅更加顺畅!
关于更多内容,大家可以关注GitCode 玄武社区[12]。官网地址[13]。
参考资料
[1]
什么是 Cargo: #什么是-cargo
[2]
安装与验证: #安装与验证
[3]
基本操作: #基本操作
[4]
项目配置详解: #项目配置详解
[5]
依赖管理: #依赖管理
[6]
高级功能: #高级功能
[7]
实战示例: #实战示例
[8]
最佳实践: #最佳实践
[9]
Cargo 官方文档: https://doc.rust-lang.org/cargo/
[10]
Cargo 参考手册: https://doc.rust-lang.org/cargo/reference/
[11]
crates.io: https://crates.io/
[12]
GitCode玄武社区: https://gitcode.com/xuanwu
[13]
官网地址: https://xuanwu.openatom.cn/