Skip to the workspace
Pebellslearn by building
Modules and Crates  ›  Lesson

Dependencies with Cargo

Dependency Management with Cargo 12 minCargo.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.

rust / Dependencies with Cargo

Explore each scene at your own pace.

01 · The rule

The rule

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.
  • features switches 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 build respects the lock file.
  • cargo update moves every locked version to the newest one still inside its range; cargo update -p chrono does just one.
  • cargo tree shows who depends on what.

Then use it in code by crate name: use chrono::NaiveDate;.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.