Cargo入门 #
一、Cargo概述 #
Cargo是Rust的官方构建工具和包管理器,它负责:
- 创建项目结构
- 管理依赖
- 编译代码
- 运行测试
- 生成文档
- 发布包
二、创建项目 #
2.1 新建可执行项目 #
bash
cargo new hello_cargo
生成的项目结构:
text
hello_cargo/
├── Cargo.toml
└── src/
└── main.rs
2.2 新建库项目 #
bash
cargo new --lib my_lib
生成的项目结构:
text
my_lib/
├── Cargo.toml
└── src/
└── lib.rs
2.3 在现有目录创建 #
bash
mkdir my_project
cd my_project
cargo init
三、Cargo.toml配置 #
3.1 基本结构 #
toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
description = "A sample project"
license = "MIT"
[dependencies]
serde = "1.0"
tokio = { version = "1.0", features = ["full"] }
[dev-dependencies]
criterion = "0.5"
[build-dependencies]
cc = "1.0"
3.2 配置字段说明 #
| 字段 | 说明 |
|---|---|
| name | 项目名称 |
| version | 版本号(语义化版本) |
| edition | Rust版本(2015/2018/2021) |
| authors | 作者列表 |
| description | 项目描述 |
| license | 许可证 |
| repository | 代码仓库地址 |
3.3 依赖版本语法 #
toml
[dependencies]
# 精确版本
serde = "=1.0.152"
# 语义化版本范围
serde = "1.0" # >=1.0.0, <2.0.0
serde = "1.0.152" # >=1.0.152, <1.1.0
serde = "^1.0" # 同上
serde = "~1.0.152" # >=1.0.152, <1.0.153
# 指定特性
tokio = { version = "1.0", features = ["full"] }
# 从git仓库
my_lib = { git = "https://github.com/user/my_lib" }
# 本地路径
my_local = { path = "../my_local" }
四、常用命令 #
4.1 构建与运行 #
bash
# 检查代码(快速)
cargo check
# 编译(debug模式)
cargo build
# 编译(release模式,优化)
cargo build --release
# 编译并运行
cargo run
# 运行release版本
cargo run --release
4.2 项目管理 #
bash
# 创建新项目
cargo new project_name
# 初始化项目
cargo init
# 添加依赖
cargo add serde
cargo add tokio --features full
# 移除依赖
cargo rm serde
# 更新依赖
cargo update
# 查看依赖树
cargo tree
4.3 测试 #
bash
# 运行所有测试
cargo test
# 运行特定测试
cargo test test_name
# 运行文档测试
cargo test --doc
# 显示测试输出
cargo test -- --nocapture
4.4 文档 #
bash
# 生成文档
cargo doc
# 生成并打开文档
cargo doc --open
# 包含依赖文档
cargo doc --document-private-items
4.5 发布 #
bash
# 打包
cargo package
# 发布到crates.io
cargo publish
# 检查发布问题
cargo publish --dry-run
五、项目结构 #
5.1 标准项目结构 #
text
my_project/
├── Cargo.toml # 项目配置
├── Cargo.lock # 依赖锁定(自动生成)
├── src/
│ ├── main.rs # 可执行入口
│ ├── lib.rs # 库入口
│ └── bin/ # 多个可执行文件
│ └── tool.rs
├── tests/ # 集成测试
│ └── integration_test.rs
├── examples/ # 示例代码
│ └── example.rs
├── benches/ # 性能测试
│ └── benchmark.rs
└── docs/ # 文档
5.2 模块组织 #
rust
// src/lib.rs
pub mod network;
pub mod utils;
// 或使用目录
// src/
// ├── lib.rs
// ├── network/
// │ ├── mod.rs
// │ └── tcp.rs
// └── utils.rs
六、工作空间 #
6.1 创建工作空间 #
toml
# Cargo.toml(工作空间根目录)
[workspace]
members = [
"crate1",
"crate2",
]
6.2 工作空间结构 #
text
workspace/
├── Cargo.toml # 工作空间配置
├── crate1/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs
├── crate2/
│ ├── Cargo.toml
│ └── src/
│ └── main.rs
└── target/ # 共享构建目录
6.3 工作空间命令 #
bash
# 构建所有成员
cargo build
# 构建特定成员
cargo build -p crate1
# 运行特定成员
cargo run -p crate2
七、特性(Features) #
7.1 定义特性 #
toml
[features]
default = ["feature1"]
feature1 = []
feature2 = ["dep1"]
[dependencies]
dep1 = { version = "1.0", optional = true }
7.2 使用特性 #
bash
# 使用默认特性
cargo build
# 不使用默认特性
cargo build --no-default-features
# 启用特定特性
cargo build --features feature1,feature2
# 启用所有特性
cargo build --all-features
7.3 代码中使用 #
rust
#[cfg(feature = "feature1")]
fn feature1_function() {
// ...
}
#[cfg(not(feature = "feature1"))]
fn feature1_function() {
// 替代实现
}
八、构建配置 #
8.1 Profile配置 #
toml
[profile.dev]
opt-level = 0 # 优化级别(0-3)
debug = true # 调试信息
debug-assertions = true
[profile.release]
opt-level = 3 # 最高优化
debug = false
lto = true # 链接时优化
codegen-units = 1 # 代码生成单元
[profile.test]
opt-level = 0
8.2 自定义Profile #
toml
[profile.release-with-debug]
inherits = "release"
debug = true
九、环境变量 #
9.1 常用环境变量 #
bash
# 设置优化级别
CARGO_PROFILE_RELEASE_OPT_LEVEL=3
# 设置目标目录
CARGO_TARGET_DIR=target
# 设置构建并行度
CARGO_BUILD_JOBS=4
# 离线模式
CARGO_NET_OFFLINE=true
9.2 在代码中使用 #
rust
option_env!("MY_ENV_VAR")
十、实践示例 #
10.1 创建完整项目 #
bash
# 创建项目
cargo new my_app
cd my_app
# 添加依赖
cargo add serde --features derive
cargo add clap --features derive
# 编写代码
# 编辑 src/main.rs
# 运行
cargo run
# 测试
cargo test
# 发布构建
cargo build --release
10.2 示例代码 #
rust
use clap::Parser;
use serde::{Deserialize, Serialize};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
#[arg(short, long)]
name: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Person {
name: String,
age: u32,
}
fn main() {
let args = Args::parse();
println!("Hello, {}!", args.name);
let person = Person {
name: args.name,
age: 25,
};
let json = serde_json::to_string(&person).unwrap();
println!("JSON: {}", json);
}
十一、常见问题 #
11.1 依赖下载慢 #
配置镜像源(见安装章节)。
11.2 编译缓存问题 #
bash
# 清理构建缓存
cargo clean
11.3 版本冲突 #
bash
# 查看依赖树
cargo tree
# 查看重复依赖
cargo tree -d
十二、总结 #
本章学习了:
- Cargo项目创建与管理
- Cargo.toml配置语法
- 依赖管理
- 常用命令
- 工作空间
- 特性配置
Cargo是Rust开发的核心工具,熟练使用它能大大提高开发效率。下一章,我们将学习Rust的基础语法。
最后更新:2026-03-27