Dependencies with Cargo
The library program needs dates for due days and a way to save the catalogue to a file. Other people have already written good crates for both. Cargo fetches them, builds them and keeps everyone on the team using the same versions, as long as you understand two files.
The rule
Cargo.toml says which versions are acceptable; Cargo.lock says which ones were chosen.
Add a dependency with a command or by editing the file:
cargo add chrono
cargo add serde --features derive[dependencies]
chrono = "0.4"
serde = { version = "1.0", features = ["derive"] }
[dev-dependencies]
proptest = "1"[dependencies]: needed to build and run your code.[dev-dependencies]: needed only for tests, examples and benchmarks.featuresswitches on optional parts of a crate.
Version requirements are ranges. A bare version means "compatible with this", following semantic versioning:
| Written | Accepts |
|---|---|
"1.0" |
1.0.0 up to, not including, 2.0.0 |
"1.2.3" |
1.2.3 up to, not including, 2.0.0 |
"0.4" |
0.4.0 up to, not including, 0.5.0 |
"=1.2.3" |
exactly 1.2.3 |
Below 1.0, the first non-zero number is treated as the breaking one, which is why "0.4" never reaches 0.5.
Cargo.lock is written on the first build. It records the exact version of every crate, including the crates your crates depend on. Anyone building from the same lock file gets the same code. Commit it for applications.
cargo buildrespects the lock file.cargo updatemoves every locked version to the newest one still inside its range;cargo update -p chronodoes just one.cargo treeshows who depends on what.
Then use it in code by crate name: use chrono::NaiveDate;.
The shortcut
For any requirement, find the leftmost non-zero number: that is the one that must not change. Everything to its right may rise.
serde = "1.0"
Leftmost non-zero is 1. Anything 1.x.y is allowed; 2.0 is not.
The trap is thinking "1.0" means exactly 1.0.0. It is a range; the lock file is what pins the exact version.
Drills
Answer fast — trust the rule.
Which versions does serde = "1.0" accept?
Can chrono = "0.4" resolve to version 0.5.2?
What does Cargo.lock record?
Where does a crate that only your tests use belong?
Remember
- Cargo.toml holds version ranges; Cargo.lock holds the exact picks;
cargo updatemoves picks within ranges. - Leftmost non-zero number is the one that cannot change.
- Test-only crates go in
[dev-dependencies].
