name: rust-cargo-assistant description: Cargo构建系统、crate管理和Rust项目配置辅助。
Rust Cargo 和 Crate 管理技能
Cargo构建系统、crate管理和Rust项目配置辅助。
指令
您是一个Rust和Cargo生态系统专家。当被调用时:
-
Cargo管理:
- 初始化和配置Cargo项目
- 管理Cargo.toml和Cargo.lock文件
- 配置构建配置文件和特性
- 处理工作空间和多crate项目
- 有效使用cargo命令
-
依赖管理:
- 添加、更新和移除crate
- 处理特性标志和可选依赖
- 使用语义版本控制和版本解析
- 管理开发、构建和目标特定依赖
- 处理路径和git依赖
-
项目设置:
- 初始化库和二进制项目
- 配置项目结构
- 设置测试和基准测试
- 配置文档
- 管理交叉编译
-
故障排除:
- 修复依赖解析错误
- 调试编译问题
- 处理版本冲突
- 清理构建产物
- 解决链接器错误
-
最佳实践:提供Rust项目组织、crate发布和性能优化的指导
Cargo基础
项目初始化
# 创建新的二进制项目
cargo new my-project
# 创建新的库
cargo new --lib my-lib
# 创建具有特定名称的项目
cargo new --name my_awesome_project my-project
# 在现有目录中初始化
cargo init
# 初始化为库
cargo init --lib
# 创建的项目结构:
# my-project/
# ├── Cargo.toml
# ├── .gitignore
# └── src/
# └── main.rs (或lib.rs用于库)
基本命令
# 构建项目
cargo build
# 使用发布优化构建
cargo build --release
# 运行项目
cargo run
# 带参数运行
cargo run -- arg1 arg2
# 运行特定二进制文件
cargo run --bin my-binary
# 检查代码(比构建更快)
cargo check
# 运行测试
cargo test
# 运行基准测试
cargo bench
# 生成文档
cargo doc --open
# 格式化代码
cargo fmt
# 代码检查
cargo clippy
# 清理构建产物
cargo clean
# 更新依赖
cargo update
# 搜索crate
cargo search tokio
# 安装二进制文件
cargo install ripgrep
使用示例
@rust-cargo-assistant
@rust-cargo-assistant --init-project
@rust-cargo-assistant --add-dependencies
@rust-cargo-assistant --optimize-build
@rust-cargo-assistant --troubleshoot
@rust-cargo-assistant --publish-crate
Cargo.toml配置
完整示例
[package]
name = "my-awesome-project"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <email@example.com>"]
description = "项目的简短描述"
documentation = "https://docs.rs/my-awesome-project"
homepage = "https://github.com/user/my-awesome-project"
repository = "https://github.com/user/my-awesome-project"
readme = "README.md"
license = "MIT OR Apache-2.0"
keywords = ["cli", "tool", "utility"]
categories = ["command-line-utilities"]
rust-version = "1.74.0"
[dependencies]
# 常规依赖
tokio = { version = "1.35", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
clap = { version = "4.4", features = ["derive"] }
# 可选依赖(特性门控)
redis = { version = "0.24", optional = true }
[dev-dependencies]
# 测试和基准测试依赖
criterion = "0.5"
mockall = "0.12"
proptest = "1.4"
[build-dependencies]
# 构建脚本依赖
cc = "1.0"
[features]
# 特性标志
default = ["json"]
json = ["serde_json"]
cache = ["redis"]
full = ["json", "cache"]
[[bin]]
# 二进制配置
name = "my-app"
path = "src/main.rs"
[lib]
# 库配置
name = "my_lib"
path = "src/lib.rs"
crate-type = ["lib", "cdylib"] # 用于FFI
[profile.release]
# 发布配置文件优化
opt-level = 3
lto = true
codegen-units = 1
strip = true
[profile.dev]
# 开发配置文件
opt-level = 0
debug = true
[workspace]
# 工作空间配置
members = ["crates/*", "examples/*"]
exclude = ["archived/*"]
依赖规范
[dependencies]
# Crates.io依赖
serde = "1.0" # ^1.0.0(最新1.x)
tokio = "1.35.0" # ^1.35.0
regex = "~1.10.0" # >=1.10.0, <1.11.0
# 版本操作符
reqwest = ">= 0.11, < 0.13"
actix-web = "= 4.4.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.0" }
my-lib = { git = "https://github.com/user/my-lib", rev = "abc123" }
# 路径依赖(本地开发)
my-local-lib = { path = "../my-local-lib" }
# 特性
tokio = { version = "1.35", features = ["full"] }
serde = { version = "1.0", features = ["derive"], default-features = false }
# 可选依赖
redis = { version = "0.24", optional = true }
# 重命名依赖
web-framework = { package = "actix-web", version = "4.4" }
# 平台特定依赖
[target.'cfg(windows)'.dependencies]
winapi = "0.3"
[target.'cfg(unix)'.dependencies]
nix = "0.27"
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "0.2"
项目结构模式
二进制项目
my-app/
├── Cargo.toml
├── Cargo.lock
├── src/
│ ├── main.rs
│ ├── lib.rs (可选)
│ ├── config.rs
│ └── utils.rs
├── tests/
│ └── integration_test.rs
├── benches/
│ └── benchmark.rs
├── examples/
│ └── example.rs
└── README.md
库项目
my-lib/
├── Cargo.toml
├── src/
│ ├── lib.rs
│ ├── error.rs
│ └── types.rs
├── tests/
│ └── lib_test.rs
├── benches/
│ └── performance.rs
├── examples/
│ └── basic_usage.rs
└── README.md
工作空间项目
workspace/
├── Cargo.toml (工作空间根)
├── crates/
│ ├── core/
│ │ ├── Cargo.toml
│ │ └── src/lib.rs
│ ├── api/
│ │ ├── Cargo.toml
│ │ └── src/lib.rs
│ └── cli/
│ ├── Cargo.toml
│ └── src/main.rs
├── examples/
│ └── demo/
│ ├── Cargo.toml
│ └── src/main.rs
└── README.md
# 工作空间Cargo.toml
[workspace]
members = [
"crates/core",
"crates/api",
"crates/cli",
]
[workspace.package]
edition = "2021"
license = "MIT OR Apache-2.0"
rust-version = "1.74.0"
[workspace.dependencies]
# 共享依赖版本
tokio = { version = "1.35", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
依赖管理
添加依赖
# 添加最新版本
cargo add serde
# 添加带特性
cargo add tokio --features full
# 添加开发依赖
cargo add --dev proptest
# 添加构建依赖
cargo add --build cc
# 添加可选依赖
cargo add redis --optional
# 从git添加
cargo add --git https://github.com/user/repo
# 添加特定版本
cargo add serde@1.0.193
更新依赖
# 更新所有依赖
cargo update
# 更新特定依赖
cargo update serde
# 更新到破坏性版本
cargo upgrade
# 检查过时依赖
cargo outdated
# 显示依赖树
cargo tree
# 显示特定包的依赖树
cargo tree -p tokio
# 显示重复依赖
cargo tree --duplicates
# 解释依赖包含原因
cargo tree -i serde
管理特性
[features]
default = ["std"]
std = []
async = ["tokio", "async-trait"]
serde = ["dep:serde", "dep:serde_json"]
full = ["std", "async", "serde"]
# 使用特定特性构建
cargo build --features async
# 使用多个特性构建
cargo build --features "async,serde"
# 使用所有特性构建
cargo build --all-features
# 构建时不使用默认特性
cargo build --no-default-features
# 构建时不使用默认但使用特定特性
cargo build --no-default-features --features std
构建配置文件和优化
配置文件配置
[profile.dev]
opt-level = 0 # 无优化
debug = true # 包含调试信息
split-debuginfo = "unpacked"
debug-assertions = true
overflow-checks = true
lto = false
panic = 'unwind'
incremental = true
codegen-units = 256
[profile.release]
opt-level = 3 # 最大优化
debug = false
strip = true # 剥离符号
lto = true # 链接时优化
codegen-units = 1 # 更好的优化
panic = 'abort' # 更小的二进制文件
[profile.release-with-debug]
inherits = "release"
debug = true
strip = false
# 自定义配置文件
[profile.production]
inherits = "release"
lto = "fat"
codegen-units = 1
opt-level = 3
# 使用特定配置文件构建
cargo build --profile production
# 发布构建
cargo build --release
# 开发构建(默认)
cargo build
大小优化
[profile.release]
opt-level = "z" # 优化大小
lto = true
codegen-units = 1
strip = true
panic = "abort"
[profile.release.package."*"]
opt-level = "z"
# 附加大小减少工具
cargo install cargo-bloat
# 显示占用空间的内容
cargo bloat --release
# 显示每个crate的大小
cargo bloat --release --crates
# 使用UPX压缩
upx --best --lzma target/release/my-app
测试和基准测试
测试
// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 2), 4);
}
#[test]
#[should_panic]
fn test_panic() {
panic!("This test should panic");
}
#[test]
#[ignore]
fn expensive_test() {
// 长时间运行测试
}
}
# 运行所有测试
cargo test
# 运行特定测试
cargo test test_add
# 运行匹配模式的测试
cargo test add
# 运行被忽略的测试
cargo test -- --ignored
# 带输出运行
cargo test -- --nocapture
# 在单线程中运行测试
cargo test -- --test-threads=1
# 运行文档测试
cargo test --doc
# 运行集成测试
cargo test --test integration_test
集成测试
// tests/integration_test.rs
use my_lib::add;
#[test]
fn integration_test() {
assert_eq!(add(5, 5), 10);
}
使用Criterion进行基准测试
[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "my_benchmark"
harness = false
// benches/my_benchmark.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use my_lib::add;
fn benchmark_add(c: &mut Criterion) {
c.bench_function("add", |b| {
b.iter(|| add(black_box(5), black_box(5)))
});
}
criterion_group!(benches, benchmark_add);
criterion_main!(benches);
# 运行基准测试
cargo bench
# 运行特定基准测试
cargo bench benchmark_add
# 保存基线
cargo bench -- --save-baseline main
# 与基线比较
cargo bench -- --baseline main
常见问题及解决方案
问题:链接器错误
# 错误:使用`cc`链接失败
# 解决方案:安装C编译器
# Ubuntu/Debian
sudo apt-get install build-essential
# macOS(安装Xcode命令行工具)
xcode-select --install
# Windows(安装Visual Studio构建工具)
# 或使用rustup:
rustup toolchain install stable-x86_64-pc-windows-gnu
问题:依赖版本冲突
# 检查依赖树
cargo tree
# 查看包的所有版本
cargo tree -i serde
# 在Cargo.toml中强制特定版本
[dependencies]
serde = "=1.0.193" # 精确版本
# 或使用工作空间统一版本
[workspace.dependencies]
serde = "1.0"
问题:编译缓慢
# 使用sccache进行缓存
cargo install sccache
export RUSTC_WRAPPER=sccache
# 添加到Cargo.toml
[profile.dev]
incremental = true
# 使用mold链接器(Linux)
sudo apt install mold
export RUSTFLAGS="-C link-arg=-fuse-ld=mold"
# 或添加到.cargo/config.toml
[target.x86_64-unknown-linux-gnu]
linker = "clang"
rustflags = ["-C", "link-arg=-fuse-ld=mold"]
# 减少开发中的代码生成单元
[profile.dev]
codegen-units = 128 # 默认是256
问题:Cargo.lock冲突
# 重新生成锁文件
rm Cargo.lock
cargo build
# 更新特定依赖
cargo update -p serde
# 对于库:不提交Cargo.lock
echo "Cargo.lock" >> .gitignore
# 对于二进制文件:始终提交Cargo.lock
问题:磁盘空间不足
# 清理构建产物
cargo clean
# 清理所有项目
cargo cache --autoclean
# 安装cargo-cache
cargo install cargo-cache
# 清理注册表缓存
cargo cache -a
交叉编译
设置目标
# 列出已安装的目标
rustup target list --installed
# 添加目标
rustup target add x86_64-unknown-linux-musl
rustup target add x86_64-pc-windows-gnu
rustup target add aarch64-unknown-linux-gnu
# 为目标构建
cargo build --target x86_64-unknown-linux-musl
交叉编译配置
# .cargo/config.toml
[target.x86_64-unknown-linux-musl]
linker = "x86_64-linux-musl-gcc"
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
使用Cross
# 安装cross
cargo install cross
# 使用cross构建
cross build --target x86_64-unknown-linux-musl
cross build --target aarch64-unknown-linux-gnu
# cross支持许多开箱即用的目标
cross build --target armv7-unknown-linux-gnueabihf
发布到Crates.io
准备发布
[package]
name = "my-crate"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <email@example.com>"]
description = "简短描述(必需)"
license = "MIT OR Apache-2.0"
repository = "https://github.com/user/my-crate"
documentation = "https://docs.rs/my-crate"
homepage = "https://github.com/user/my-crate"
readme = "README.md"
keywords = ["cli", "tool"] # 最多5个
categories = ["command-line-utilities"] # 来自crates.io列表
# 从包中排除文件
exclude = [
"tests/*",
"examples/*",
".github/*",
"*.sh",
]
# 或指定要包含的内容
include = [
"src/**/*",
"Cargo.toml",
"README.md",
"LICENSE*",
]
发布工作流
# 登录到crates.io
cargo login <your-api-token>
# 发布前检查包
cargo package
# 列出将发布的文件
cargo package --list
# 测试包
cargo package --verify
# 发布(先进行干运行)
cargo publish --dry-run
# 实际发布
cargo publish
# 撤回版本(从新依赖中移除)
cargo yank --vers 0.1.0
# 取消撤回版本
cargo yank --vers 0.1.0 --undo
版本控制策略
# 更新版本
# 在Cargo.toml中,更新版本字段
# 破坏性更改(0.1.0 -> 1.0.0)
# 主版本号增加
# 新特性(1.0.0 -> 1.1.0)
# 次版本号增加
# 错误修复(1.1.0 -> 1.1.1)
# 补丁版本号增加
# 预发布版本
0.1.0-alpha.1
0.1.0-beta.1
0.1.0-rc.1
有用的Cargo工具
cargo-edit
# 安装
cargo install cargo-edit
# 添加依赖
cargo add serde
# 移除依赖
cargo rm serde
# 升级依赖
cargo upgrade
cargo-watch
# 安装
cargo install cargo-watch
# 监视并重新构建更改
cargo watch
# 监视并运行测试
cargo watch -x test
# 监视并运行
cargo watch -x run
# 每次运行时清除屏幕
cargo watch -c -x run
cargo-expand
# 安装
cargo install cargo-expand
# 展开宏
cargo expand
# 展开特定模块
cargo expand module::path
cargo-audit
# 安装
cargo install cargo-audit
# 审计依赖的安全性漏洞
cargo audit
# 修复漏洞
cargo audit fix
cargo-outdated
# 安装
cargo install cargo-outdated
# 检查过时依赖
cargo outdated
# 显示详细信息
cargo outdated -v
cargo-tarpaulin(代码覆盖)
# 安装
cargo install cargo-tarpaulin
# 生成覆盖报告
cargo tarpaulin --out Html
# 带详细输出
cargo tarpaulin --verbose --out Html
高级Cargo特性
构建脚本
[package]
build = "build.rs"
[build-dependencies]
cc = "1.0"
// build.rs
fn main() {
// 编译C代码
cc::Build::new()
.file("src/native/foo.c")
.compile("foo");
// 发出cargo指令
println!("cargo:rerun-if-changed=src/native/foo.c");
println!("cargo:rustc-link-lib=static=foo");
}
Cargo别名
# .cargo/config.toml
[alias]
b = "build"
c = "check"
t = "test"
r = "run"
rr = "run --release"
br = "build --release"
wr = "watch -x run"
# 使用别名
cargo b # 同cargo build
cargo rr # 同cargo run --release
环境变量
# 离线模式
cargo build --offline
# 自定义注册表
export CARGO_REGISTRY_DEFAULT=my-registry
# 自定义目标目录
export CARGO_TARGET_DIR=/tmp/cargo-target
# 附加rustc标志
export RUSTFLAGS="-C target-cpu=native"
# 构建作业
export CARGO_BUILD_JOBS=4
最佳实践总结
项目组织
- 对于多crate项目使用工作空间
- 使用src/存放源代码
- 使用tests/进行集成测试
- 使用benches/进行基准测试
- 使用examples/提供使用示例
- 包含全面的README.md
依赖管理
- 使用语义版本控制
- 为二进制文件提交Cargo.lock
- 不为库提交Cargo.lock
- 最小化依赖
- 使用特性用于可选功能
- 定期审计依赖
性能
- 生产环境使用发布配置文件
- 启用LTO以获得更小的二进制文件
- 考虑codegen-units = 1以优化
- 使用cargo-bloat分析二进制大小
- 优化前进行性能分析
测试
- 在每个模块中编写单元测试
- 在tests/中编写集成测试
- 使用文档测试提供示例
- 追求高测试覆盖
- 在CI/CD中运行测试
发布
- 严格遵循semver
- 记录破坏性更改
- 在文档中包含示例
- 选择适当的关键词和类别
- 发布前测试包
- 维护CHANGELOG.md
快速参考命令
# 项目管理
cargo new <name> # 创建新项目
cargo init # 在当前目录初始化
cargo build # 构建项目
cargo run # 构建并运行
cargo check # 检查而不构建
# 依赖
cargo add <crate> # 添加依赖
cargo update # 更新依赖
cargo tree # 显示依赖树
# 测试和质量
cargo test # 运行测试
cargo bench # 运行基准测试
cargo fmt # 格式化代码
cargo clippy # 代码检查
cargo doc --open # 生成并打开文档
# 维护
cargo clean # 清理构建产物
cargo publish # 发布到crates.io
cargo install <crate> # 安装二进制文件
# 高级
cargo build --release # 优化构建
cargo build --target <target> # 交叉编译
cargo package # 创建发布包
备注
- 始终为二进制文件和应用程序提交Cargo.lock
- 使用工作空间在crate间共享依赖
- 为生产环境启用LTO并优化codegen-units
- 定期运行cargo clippy以提高代码质量
- 使用cargo fmt保持一致的样式
- 审计依赖的安全性漏洞
- 发布前在多个平台测试
- 严格遵循语义版本控制
- 彻底文档化所有公共API
- 使用特性用于可选功能