Skip to content

依赖

cargo add 写入 Cargo.toml 并更新 Cargo.lock

bash
cargo add serde --features derive
cargo add tokio --features macros,rt-multi-thread,net
cargo add --dev pretty_assertions

版本需求默认是 ^ 语义:1 表示 >=1.0.0 <2.0.0Cargo.lock 钉死实际编译的精确版本。二进制和应用仓库提交 lock;纯库是否提交 lock 看协作约定,应用侧必须以 lock 为准复现构建。

features

Cargo feature 是编译期开关,用来裁剪可选依赖和代码路径:

toml
[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
serde = { version = "1", features = ["derive"] }

full 类 feature 方便试跑,正式包按实际用到的能力勾选,减少编译量和二进制体积。本包对外提供 feature 时写在 [features],默认 feature 保持最小。

来源

toml
[dependencies]
local = { path = "../local" }
git-dep = { git = "https://github.com/example/demo", tag = "v1.0.0" }

path 用于同仓库或本地联调。git 依赖要钉 tag / rev,不要长期盯着默认分支。workspace 内共享版本用 [workspace.dependencies],成员写 foo.workspace = true

临时覆盖上游时用 [patch],只留在本地或短期分支,不要变成长期版本管理手段。

项目里常见的 crate

crate角色
serde序列化;几乎总是开 derive
tokio异步运行时
anyhow应用侧错误传播
thiserror库侧错误类型
clapCLI 参数
reqwestHTTP 客户端
tracing结构化日志与 span

选 crate 时看是否维护、feature 能否裁剪、同步还是异步 API 是否与当前运行时一致。标准库能覆盖的不要再加依赖。

基于 MIT 许可发布