Day 19: 包与Cargo
1. Cargo 简介
Section titled “1. Cargo 简介”Cargo是Rust的包管理器和构建工具,是Rust生态系统的核心。掌握Cargo意味着掌握Rust项目管理的精髓。
Cargo的主要功能:
- 创建和管理项目
- 管理依赖
- 构建项目
- 运行测试
- 发布到 crates.io
2. 创建项目
Section titled “2. 创建项目”# 创建可执行项目cargo new my_project
# 创建库项目cargo new --lib my_library
# 目录结构my_project/├── Cargo.toml├── src/│ └── main.rs└── .git/3. Cargo.toml 结构
Section titled “3. Cargo.toml 结构”[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 = truecodegen-units = 1panic = "abort"strip = true4. 常用 Cargo 命令
Section titled “4. 常用 Cargo 命令”# 构建项目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 # 获取帮助5. 依赖管理示例
Section titled “5. 依赖管理示例”// 添加依赖后,自动下载并编译// 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);}6. 工作空间(Workspace)
Section titled “6. 工作空间(Workspace)”工作空间允许管理多个相关 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"# 创建工作空间mkdir -p crates/core crates/cli crates/server
# 各自有 Cargo.toml# crates/core/Cargo.toml# [package]# name = "my_core"# version.workspace = true# edition.workspace = true7. 发布到 crates.io
Section titled “7. 发布到 crates.io”# 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 # 正式发布8. Cargo.lock 和 .cargo/config.toml
Section titled “8. Cargo.lock 和 .cargo/config.toml”# 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开发的核心工具。明天我们将学习测试,包括单元测试、集成测试和文档测试。