Dependencies with Cargo
Cargo.toml states which crates and version ranges a package accepts, Cargo.lock records the exact versions chosen, and cargo add and cargo update manage both.
Add a dependency and distinguish version requirements from a recorded resolution.
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;.