Cargo 教程

Cargo.toml、依赖管理、features、workspace、以及常用命令。

Beginner
Key PointsCargo 同时是构建工具、包管理器、测试运行器和文档生成器。

项目结构

Text
hello/
├── Cargo.toml        ← 项目清单
├── Cargo.lock        ← 精确版本锁(可执行程序要提交)
├── src/
│   ├── main.rs       ← 二进制入口
│   └── lib.rs        ← 库入口
├── tests/            ← 集成测试
├── benches/          ← 基准测试
└── examples/         ← 示例

Cargo.toml

TOML
[package]
name = "hello"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
description = "一个示例项目"
license = "MIT"

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

[dev-dependencies]
criterion = "0.5"

[profile.release]
opt-level = 3
lto = true
strip = true

[[bin]]
name = "hello"
path = "src/main.rs"

常用命令

Bash
cargo new myapp              # 新建二进制项目
cargo new mylib --lib        # 新建库项目
cargo build                  # 调试构建
cargo build --release        # 优化构建
cargo run                    # 构建并运行
cargo test                   # 跑测试
cargo doc --open             # 生成并打开文档
cargo fmt                    # 格式化
cargo clippy                 # 静态检查
cargo add serde              # 加依赖(1.62+ 内置)
cargo update                 # 升级到兼容的最新版
cargo tree                   # 依赖树
cargo clean                  # 清 target/
Output
$ cargo add serde --features derive
      Adding serde v1.0.215 to dependencies
             Features:
             + derive

features

TOML
[dependencies]
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }

default-features = false disables defaults so you enable only what you need. This matters a lot for build time and binary size — reqwest defaults to OpenSSL; rustls-tls avoids the system dependency.

workspace

TOML
# 根 Cargo.toml
[workspace]
members = ["crates/api", "crates/core", "crates/cli"]
resolver = "2"

[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
TOML
# crates/api/Cargo.toml
[dependencies]
serde = { workspace = true }
tokio = { workspace = true }
core = { path = "../core" }

A workspace shares one target/ and one set of dependency versions, so builds are faster and versions cannot diverge. workspace.dependencies is the single place for versions.

测试与文档

Rust
// src/lib.rs
/// 两数相加。
///
/// # 示例
///
/// ```
/// assert_eq!(add(1, 2), 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(add(2, 2), 4);
    }
}
Output
$ cargo test
running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored

Code blocks in doc comments are **executed by cargo test**, so examples cannot rot. That is why Rust documentation is unusually trustworthy.

Friends & Partners