Cargo 深入
Cargo.toml 依赖/features/build-dependencies、workspace 工作空间
Cargo 深入
Cargo.toml 不仅声明依赖——features、workspace、build-dependencies 是真实项目的必备知识。
学完本章你将: 掌握 Cargo.toml 依赖/features、workspace 工作空间。
依赖声明
toml
[dependencies]
serde = "1.0" # 语义版本
serde = { version = "1.0", features = ["derive"] } # 带 features
rand = { git = "https://github.com/rust-lang/rand" } # Git 依赖
[dev-dependencies]
criterion = "0.5" # 只在测试/基准中使用
[build-dependencies]
cc = "1.0" # 只在构建脚本中使用
Features —— 条件编译
toml
[features]
default = ["std"]
std = []
serde = ["dep:serde", "serde/derive"] # 可选依赖
rust
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
Workspace —— 管理多 crate
toml
# 根 Cargo.toml
[workspace]
members = [
"core", # 核心库
"cli", # CLI 工具
"web", # Web 服务
]
resolver = "2"
bash
myapp/
├── Cargo.toml # workspace 定义
├── core/
│ └── Cargo.toml
├── cli/
│ └── Cargo.toml
└── web/
└── Cargo.toml