Cargo 项目管理
学习目标
- 理解 Cargo.toml 的结构
- 掌握
cargo build、cargo run、cargo check的区别 - 学会添加和管理依赖
- 理解 debug 和 release 构建模式
核心概念
Cargo.toml 配置文件
[package]
name = "my_project" # 项目名
version = "0.1.0" # 语义化版本
edition = "2021" # Rust 版本(2015/2018/2021/2024)
authors = ["You <you@example.com>"]
description = "我的项目"
[dependencies]
serde = "1.0" # 添加依赖
serde_json = "1.0"
tokio = { version = "1", features = ["full"] } # 带 feature 的依赖
核心命令
cargo new my_app # 创建二进制项目
cargo new my_lib --lib # 创建库项目
cargo build # 编译(debug 模式)
cargo build --release # 编译(release 模式,优化)
cargo run # 编译并运行
cargo check # 只检查语法,不生成二进制(最快)
cargo test # 运行测试
cargo doc --open # 生成并打开文档
Debug vs Release
cargo build # debug: 编译快,运行慢,有调试信息
cargo build --release # release: 编译慢,运行快,优化彻底
# 产物位置
# debug: target/debug/my_app
# release: target/release/my_app
依赖管理
添加依赖
# 方式一:命令行添加(推荐)
cargo add serde --features derive
cargo add tokio --features full
# 方式二:手动编辑 Cargo.toml
Cargo.lock
Cargo.lock锁定依赖的精确版本- 二进制项目:提交到 git(保证团队一致)
- 库项目:不提交(让使用者决定版本)
常用依赖
[dependencies]
serde = { version = "1", features = ["derive"] } # 序列化
tokio = { version = "1", features = ["full"] } # 异步运行时
reqwest = { version = "0.12", features = ["json"] } # HTTP 客户端
clap = { version = "4", features = ["derive"] } # 命令行解析
anyhow = "1" # 错误处理
实践练习
练习 1:创建并运行项目
cargo new cargo_practice
cd cargo_practice
cargo run
练习 2:添加依赖并使用
# Cargo.toml
[dependencies]
chrono = "0.4"
// src/main.rs
use chrono::Local;
fn main() {
let now = Local::now();
println!("当前时间: {}", now.format("%Y-%m-%d %H:%M:%S"));
}
练习 3:对比构建速度
time cargo build # 记录 debug 编译时间
time cargo build --release # 记录 release 编译时间
time cargo check # 记录 check 时间
常见错误
1. 依赖版本冲突
# ❌ 两个库依赖同一个 crate 的不兼容版本
[dependencies]
lib_a = "1.0" # 依赖 serde 1.0
lib_b = "2.0" # 依赖 serde 2.0(假设不兼容)
# ✅ 解决:统一版本
2. 忘记 --features
// ❌ 编译错误:找不到 Serialize trait
use serde::Serialize;
// ✅ 需要在 Cargo.toml 启用 derive feature
// serde = { version = "1", features = ["derive"] }
3. 项目名用连字符
# ❌ crate 名不能有连字符
name = "my-project"
# ✅ 用下划线
name = "my_project"
小结
| 命令 | 用途 |
|---|---|
cargo new | 创建新项目 |
cargo build | 编译 |
cargo run | 编译并运行 |
cargo check | 快速语法检查 |
cargo add | 添加依赖 |
cargo test | 运行测试 |
| 文件 | 说明 |
|---|---|
Cargo.toml | 项目配置和依赖声明 |
Cargo.lock | 依赖版本锁定(二进制项目提交) |
src/main.rs | 入口文件 |
src/lib.rs | 库入口(库项目) |
练习编辑器
rust
Loading...