Answer#
A dependency has two records. Cargo.toml states which versions you accept (serde_json = "1.0.154" means 1.0.154 or any later 1.x). Cargo.lock records the exact versions that were chosen, including the dependencies of your dependencies. Cargo edits both for you.
How to do it#
- Add a crate. Cargo looks up the newest version, writes the line, and lists the crate's optional features.
> cargo add serde_json
Updating crates.io index
Adding serde_json v1.0.154 to dependencies
Features:
+ std
- alloc
- arbitrary_precision
- float_roundtrip
- indexmap
- preserve_order
- raw_value
- unbounded_depth
Updating crates.io index
Locking 11 packages to latest Rust 1.93.0 compatible versions
[dependencies]
serde_json = "1.0.154"- Use it, and run.
fn main() {
let v: serde_json::Value = serde_json::json!({"ok": true});
println!("{v}");
}> cargo run -q
{"ok":true}- See what it brought along. Everything below
serde_jsonis a transitive dependency that you did not ask for.
> cargo tree
depdemo v0.1.0 (C:\dev\depdemo)
└── serde_json v1.0.154
├── itoa v1.0.19
├── memchr v2.8.3
├── serde_core v1.0.229
└── zmij v1.0.23cargo tree -i itoa (invert) answers the opposite question, "who needs this crate?":
itoa v1.0.19
└── serde_json v1.0.154
└── depdemo v0.1.0 (C:\dev\depdemo)- Remove it again.
cargo removeeditsCargo.tomland the unused crates leaveCargo.lockthe next time Cargo runs.
> cargo remove serde_json
Removing serde_json from dependencies
name = "depdemo"
version = "0.1.0"
edition = "2024"- To pick up newer compatible versions of everything, run
cargo update. For one crate:cargo update -p serde_json.
Why it works#
A version requirement like "1.0.154" is shorthand for ^1.0.154: compatible updates are allowed, breaking ones are not. That is why cargo update is normally safe, and why moving to a new major version (2.0) is an edit you make yourself.
Common mistakes#
- Not committing
Cargo.lockfor an application. Without it, two builds a month apart can use different versions. (Libraries commonly leave it out, because the user's own lock file decides.) - Naming a package like a folder Cargo uses. A binary called
depsis refused, becausetarget/debug/depsalready exists. - Adding a crate for a one-line job. Every dependency is more code to compile and to trust.
In Ruststudio#
Run > Cargo: Add Dependency... adds a crate, Run > Cargo: Update Dependencies updates, and Run > Cargo: Show Dependency Tree shows the tree. Under Tools, Cargo: Security Audit (cargo audit), Cargo: Check Outdated Dependencies, Cargo: Find Unused Dependencies (cargo machete) and Cargo: Check Licenses and Bans (cargo deny) run those tools; they must be installed.