Skip to content

Day 19: 包与Cargo

Cargo是Rust的包管理器和构建工具,是Rust生态系统的核心。掌握Cargo意味着掌握Rust项目管理的精髓。

Cargo的主要功能:

  • 创建和管理项目
  • 管理依赖
  • 构建项目
  • 运行测试
  • 发布到 crates.io
Terminal window
# 创建可执行项目
cargo new my_project
# 创建库项目
cargo new --lib my_library
# 目录结构
my_project/
├── Cargo.toml
├── src/
│ └── main.rs
└── .git/
[package]
name = "my_project"
version = "0.1.0"
edition = "2021" # Rust 版本
authors = ["Author <author@example.com>"]
description = "一个示例项目"
license = "MIT OR Apache-2.0"
repository = "https://github.com/author/my_project"
keywords = ["example", "tutorial"]
categories = ["command-line-utilities"]
[dependencies]
# 精确版本
regex = "1.10.0"
# 范围版本
serde = ">=1.0, <2.0"
# 使用版本元组
rand = "0.8"
# 从 git 仓库
# clap = { git = "https://github.com/clap-rs/clap", branch = "master" }
[dev-dependencies]
# 开发依赖,仅测试和示例使用
tempfile = "3.8"
[build-dependencies]
# 构建脚本依赖
build-util = "0.4"
[profile.release]
# 发布配置优化
lto = true
codegen-units = 1
panic = "abort"
strip = true
Terminal window
# 构建项目
cargo build # Debug 构建
cargo build --release # Release 构建
# 运行项目
cargo run # 运行可执行项目
cargo run --release # Release 模式运行
# 测试
cargo test # 运行所有测试
cargo test --lib # 仅运行库测试
cargo test <test_name> # 运行指定测试
# 代码检查和格式化
cargo check # 快速类型检查
cargo clippy # 静态分析建议
cargo fmt # 格式化代码
# 依赖管理
cargo add <package> # 添加依赖
cargo remove <package> # 移除依赖
cargo update # 更新依赖版本
cargo tree # 查看依赖树
# 文档和帮助
cargo doc --open # 生成并打开文档
cargo help # 获取帮助
// 添加依赖后,自动下载并编译
// Cargo.toml:
// [dependencies]
// serde = "1.0"
// serde_json = "1.0"
// rand = "0.8"
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Person {
name: String,
age: u32,
email: String,
}
fn main() {
// 使用 serde_json 解析 JSON
let json = r#"{"name": "张三", "age": 30, "email": "zhang@example.com"}"#;
let person: Person = serde_json::from_str(json).expect("JSON 解析失败");
println!("姓名: {}", person.name);
println!("年龄: {}", person.age);
println!("邮箱: {}", person.email);
// 序列化回 JSON
let output = serde_json::to_string_pretty(&person).unwrap();
println!("\nJSON 输出:\n{}", output);
}

工作空间允许管理多个相关 crate:

# Cargo.toml (根目录)
[workspace]
members = [
"crates/core",
"crates/cli",
"crates/server",
]
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "MIT"
# 共享依赖(可选)
[workspace.dependencies]
logging = "0.4"
Terminal window
# 创建工作空间
mkdir -p crates/core crates/cli crates/server
# 各自有 Cargo.toml
# crates/core/Cargo.toml
# [package]
# name = "my_core"
# version.workspace = true
# edition.workspace = true
Terminal window
# 1. 登录 crates.io 获取 API Token
# 2. 登录本地
cargo login <API_TOKEN>
# 3. 添加元数据到 Cargo.toml
[package]
name = "my_awesome_crate"
version = "0.1.0"
description = "一个超赞的 Rust 包"
license = "MIT"
repository = "https://github.com/author/my_awesome_crate"
readme = "README.md"
keywords = ["awesome", "library"]
categories = ["algorithms", "data-structures"]
# 4. 发布
cargo publish
# 5. 版本更新
# 修改 version 后
cargo publish --dry-run # 预览
cargo publish # 正式发布
Terminal window
# Cargo.lock - 自动生成,锁定依赖版本
# 提交到 git,确保构建可重现
# .cargo/config.toml - 本地配置
# 镜像配置(针对国内用户)
[source.crates-io]
replace-with = "ustc"
[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
# 或
registry = "https://mirrors.ustc.edu.cn/crates.io-index"

今天我们学习了Cargo包管理器:

  • 项目创建:cargo new 创建可执行项目,cargo new --lib 创建库
  • Cargo.toml:包元数据、依赖管理、profile 配置
  • 常用命令:build、run、test、check、clippy、fmt
  • 依赖管理:cargo add 添加依赖,支持精确版本、范围版本、git源
  • 工作空间:管理多个相关 crate,共享配置和依赖
  • 发布流程:配置元数据、cargo login、cargo publish

Cargo是Rust开发的核心工具。明天我们将学习测试,包括单元测试、集成测试和文档测试。