跳到主要内容

Rust Cargo 完全指南

包含 Workspace 管理、性能优化、发布策略等高级主题

目录

  1. Cargo 基础
  2. 插件模块 - cargo-edit
  3. Workspace 工作区管理
  4. 交叉编译
  5. 快捷键设置
  6. 性能优化
  7. 常用命令参考

Cargo 基础

什么是 Cargo?

Cargo 是 Rust 的包管理和构建工具。

基本命令

cargo new my_project # 创建新项目
cargo init # 初始化当前目录
cargo build # 调试模式构建
cargo build --release # 发布模式构建
cargo run # 运行项目
cargo test # 运行测试
cargo check # 检查代码
cargo clean # 清理编译产物

插件模块 - cargo-edit

安装

cargo install cargo-edit

常用命令

cargo add - 添加依赖

cargo add cargo-edit # 添加最新稳定版
cargo add cargo-edit@0.13.0 # 指定特定大版本
cargo add cargo-edit --features "vendored-openssl" # 开启特定特性
cargo add -D cargo-edit # 添加为开发依赖 (dev-dependencies)
cargo add -B cargo-edit # 添加为构建依赖 (build-dependencies)

cargo upgrade - 升级依赖

# ✨ 洁癖必跑:详细预检
# 查看哪些组件有新版,并区分兼容(Compatible)与不兼容(Incompatible)
cargo upgrade --dry-run --verbose

# 稳健执行:自动将 Cargo.toml 更新到最新的兼容版本
cargo upgrade --verbose

# 强力对齐:强制 Cargo.toml 的版本号与 Cargo.lock 保持完全一致
cargo upgrade --to-lockfile

# 激进跨代:尝试升级到不兼容的大版本(需手动处理 Breaking Changes)
cargo upgrade --incompatible

cargo remove - 移除依赖

cargo remove cargo-edit # 从项目中移除依赖
cargo remove --dry-run cargo-edit # 模拟移除,查看影响

Workspace 工作区管理

什么是 Workspace?

Workspace 是一个包含多个 Rust 项目的工作区。所有项目共享一个 Cargo.lock 和依赖版本,便于管理大型项目。

创建 Workspace

方法 1:从零开始

mkdir my_workspace
cd my_workspace
mkdir -p crates/{core,cli,lib}

创建根目录 Cargo.toml

[workspace]
members = ["crates/core", "crates/cli", "crates/lib"]
resolver = "2"

[workspace.package]
# 共享的元数据
version = "0.1.0"
edition = "2021"
authors = ["Your Name <your.email@example.com>"]
license = "MIT"

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

方法 2:添加成员到现有 Workspace

# 在 workspace 根目录执行
cargo new crates/new_member

然后编辑 Cargo.toml,添加到 members 列表。

Workspace 配置详解

[workspace]
# 工作区成员
members = [
"crates/core",
"crates/cli",
"crates/lib",
]

# 默认构建成员(不指定时)
default-members = ["crates/cli"]

# 解析器版本(推荐使用 "2")
resolver = "2"

# 排除特定目录
exclude = ["crates/experimental"]

[workspace.package]
# 所有成员可共享的元数据
version = "0.1.0"
edition = "2021"
authors = ["Team <team@example.com>"]
license = "MIT"
repository = "https://github.com/user/repo"
homepage = "https://example.com"
documentation = "https://docs.example.com"

[workspace.dependencies]
# 共享依赖版本管理
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
anyhow = "1.0"

成员项目配置

每个成员的 Cargo.toml

[package]
name = "my-core"
version.workspace = true # 继承 workspace 版本
edition.workspace = true
authors.workspace = true
license.workspace = true

[dependencies]
serde.workspace = true # 使用 workspace 依赖
tokio.workspace = true
anyhow.workspace = true

[dev-dependencies]
criterion = "0.5"

Workspace 命令

# 构建所有成员
cargo build

# 构建特定成员
cargo build -p my-core
cargo build --package my-cli

# 运行特定成员的可执行文件
cargo run -p my-cli -- args

# 测试所有成员
cargo test

# 测试特定成员
cargo test -p my-core

# 格式化所有成员
cargo fmt --all

# Clippy 检查所有成员
cargo clippy --all

# 查看 workspace 结构
cargo tree

# 生成所有成员的文档
cargo doc --all --no-deps --open

工作区最佳实践

1. 清晰的目录结构

my_workspace/
├── Cargo.toml
├── Cargo.lock
├── crates/
│ ├── core/
│ │ ├── Cargo.toml
│ │ └── src/
│ ├── cli/
│ │ ├── Cargo.toml
│ │ └── src/
│ └── lib/
│ ├── Cargo.toml
│ └── src/
└── README.md

2. 共享依赖版本

# Cargo.toml (根)
[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }

# crates/*/Cargo.toml
[dependencies]
serde.workspace = true # 自动使用 workspace 版本
tokio.workspace = true

3. 成员间依赖

# crates/cli/Cargo.toml
[dependencies]
my-core = { path = "../core" }
my-lib = { path = "../lib" }

4. 统一的发布策略

[workspace.metadata.publish]
# 发布哪些成员
members = ["my-core", "my-cli"]

实例:多层次 Workspace

# 根 Cargo.toml
[workspace]
members = [
"crates/core", # 核心库
"crates/macros", # 过程宏
"crates/cli", # CLI 工具
"examples/*", # 示例
"benches", # 基准测试
]

[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
clap = { version = "4.0", features = ["derive"] }
# 构建只能单独构建的示例
cargo build -p example-1

# 运行特定示例
cargo run -p example-2

# 基准测试
cargo bench -p benches

交叉编译

安装目标三元组

# Windows
rustup target add x86_64-pc-windows-gnu
rustup target add x86_64-pc-windows-msvc
rustup target add aarch64-pc-windows-msvc

# Linux
rustup target add x86_64-unknown-linux-musl
rustup target add aarch64-unknown-linux-gnu
rustup target add armv7-unknown-linux-gnueabihf

# macOS
rustup target add x86_64-apple-darwin
rustup target add aarch64-apple-darwin

编译目标

# Windows
cargo build --target x86_64-pc-windows-gnu --release

# Linux ARM64
cargo build --target aarch64-unknown-linux-gnu --release

# macOS
cargo build --target aarch64-apple-darwin --release

配置 .cargo/config.toml

[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
ar = "x86_64-w64-mingw32-ar"

[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
ar = "aarch64-linux-gnu-ar"

快捷键设置

.cargo/config.toml 别名

[alias]
# 基础
b = "build"
r = "run"
t = "test"
c = "check"
f = "fmt"
l = "clippy --all -- -D warnings"

# 发布
rel = "build --release"
rel-all = "build --release --all"

# 交叉编译
win = "build --target x86_64-pc-windows-gnu --release"
arm64-linux = "build --target aarch64-unknown-linux-gnu --release"
musl = "build --target x86_64-unknown-linux-musl --release"

# 多平台
build-all = """
build --release --target x86_64-pc-windows-gnu
&& build --release --target aarch64-unknown-linux-gnu
&& build --release --target x86_64-unknown-linux-musl
"""

# Workspace
wa = "build --all"
ta = "test --all"
ca = "check --all"
fa = "fmt --all"
da = "doc --all --no-deps --open"

使用别名

cargo b # cargo build
cargo rel # cargo build --release
cargo win # cargo build --target x86_64-pc-windows-gnu --release
cargo ta # cargo test --all

性能优化

构建配置优化

# Cargo.toml

[profile.dev]
# 调试模式(快速编译)
opt-level = 0
debug = true
split-debuginfo = "packed"

[profile.release]
# 发布模式(最优性能)
opt-level = 3
lto = true # 启用 LTO
codegen-units = 1 # 单线程编译(更好的优化)
strip = true # 剥离符号

[profile.release-with-debug]
# 发布 + 调试信息
inherits = "release"
debug = true
strip = false

[profile.bench]
# 基准测试
inherits = "release"

# 针对特定依赖的优化
[profile.release.package.my-dep]
opt-level = 2

编译加速技巧

# 使用 mold/lld 加速链接
RUSTFLAGS="-C link-arg=-fuse-ld=lld" cargo build --release

# 启用并行前端
RUSTFLAGS="-Z threads=$(nproc)" cargo build --release

# 使用 cranelift 后端(快速编译)
rustup install nightly
RUSTFLAGS="-Z cranelift" cargo +nightly build

# 增量编译
cargo build --incremental

# 检查语法(不编译)
cargo check

# 并行运行测试
cargo test -- --test-threads=4

Cargo.toml 依赖优化

[dependencies]
# 只使用需要的特性
tokio = { version = "1.0", features = ["rt-multi-thread"] }

# 使用 default-features = false 减少编译时间
serde = { version = "1.0", default-features = false, features = ["derive"] }

# 使用 optional 依赖
optional-feature = { version = "1.0", optional = true }

[features]
default = []
with-optional = ["optional-feature"]

常用命令参考

项目管理

命令说明
cargo new <name>创建新项目
cargo init初始化项目
cargo build调试构建
cargo build --release发布构建
cargo run运行项目
cargo check检查代码
cargo clean清理编译产物

Workspace

命令说明
cargo build --all构建所有成员
cargo test --all测试所有成员
cargo build -p pkg构建特定成员
cargo tree显示 Workspace 树
cargo metadata获取元数据

依赖管理

命令说明
cargo add <crate>添加依赖
cargo upgrade升级依赖
cargo remove <crate>移除依赖
cargo update更新 Cargo.lock
cargo tree显示依赖树

代码质量

命令说明
cargo fmt格式化代码
cargo clippyLint 检查
cargo test运行测试
cargo bench运行基准测试
cargo doc --open生成并打开文档

实际示例

示例 1:创建多 Crate Workspace

# 初始化
mkdir my_project
cd my_project
cargo new --lib crates/core
cargo new crates/cli
mkdir -p examples benches

# 创建根 Cargo.toml
cat > Cargo.toml << 'EOF'
[workspace]
members = ["crates/core", "crates/cli"]
resolver = "2"

[workspace.package]
version = "0.1.0"
edition = "2021"
authors = ["Your Name <your@email.com>"]

[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["full"] }
EOF

# CLI 依赖 core
cat > crates/cli/Cargo.toml << 'EOF'
[package]
name = "my-cli"
version.workspace = true
edition.workspace = true

[dependencies]
my-core = { path = "../core" }
tokio.workspace = true
EOF

# 构建
cargo build --all --release

示例 2:交叉编译所有平台

#!/bin/bash
# build-all.sh

targets=(
"x86_64-pc-windows-gnu"
"x86_64-unknown-linux-gnu"
"x86_64-unknown-linux-musl"
"aarch64-unknown-linux-gnu"
"aarch64-apple-darwin"
)

for target in "${targets[@]}"; do
echo "Building for $target..."
cargo build --release --target "$target" || exit 1
done

echo "All targets built successfully!"
chmod +x build-all.sh
./build-all.sh

示例 3:性能优化构建

# 使用 mold 链接器 + LTO 最大优化
RUSTFLAGS="-C link-arg=-fuse-ld=mold" \
cargo build \
--release \
-Z build-std=std,panic_abort \
-Z build-std-features=panic_immediate_abort \
--target x86_64-unknown-linux-gnu

常见问题解决

问题解决方案
编译太慢使用 mold/lld 链接器、启用增量编译
Workspace 成员编译冲突检查依赖版本、使用 resolver = "2"
交叉编译失败安装对应平台工具链、配置正确的 linker
cargo-edit 命令找不到cargo install cargo-edit --force

相关资源


最后更新: 2026-03-30
作者: ArcMantis