Sub topic 8
Adding and Managing Dependencies
This chapter assumes you can run cargo build and cargo run, and that you know what a package and a crate are from the earlier chapters. It covers how a package declares the external crates it uses, how Cargo resolves versions, and the errors you are most likely to meet.
What a dependency is
A dependency is another crate that your package uses. Cargo downloads it, compiles it, and links it into your crate. You declare dependencies in the [dependencies] table of Cargo.toml. After that, you refer to the crate by name in your code, the same way you refer to std.
The default source is crates.io, the public registry. Cargo can also take dependencies from a local path or from a Git repository.
Adding a dependency
The simplest way is the cargo add command:
cargo add serde --features derive
cargo add pretty_assertions --dev
cargo add [email protected]Each command edits Cargo.toml for you. --dev writes to [dev-dependencies]. You can also edit the file by hand. The manifest below declares several kinds of dependency at once.
[package]
name = "my_geometry"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
rand = "0.8"
core = { path = "../core" }
[dev-dependencies]
pretty_assertions = "1"
[features]
default = []
serde = ["dep:serde"]This manifest shows three ideas.
rand = "0.8"is the short form. It is a crates.io dependency with a version requirement.serde = { ... }is the table form. It lets you set features, mark the dependency optional, and set other fields.core = { path = "../core" }is a path dependency. It points at a crate in another directory.
The [features] table and optional = true are covered in the features chapter. The [dev-dependencies] table has its own chapter.
Version requirements
A string such as "0.8" is not an exact version. It is a requirement, and Cargo treats it as a caret requirement by default. A caret requirement allows any version that is semver-compatible with the one you wrote. Semver is the versioning convention in which the leftmost non-zero number marks the compatibility boundary.
| Written | Means | Accepts | Rejects |
|---|---|---|---|
| `"1.2.3"` | `^1.2.3` | `1.2.3` up to but not including `2.0.0` | `2.0.0`, `1.2.2` |
| `"1.2"` | `^1.2` | `1.2.0` up to but not including `2.0.0` | `2.0.0`, `1.1.9` |
| `"0.8"` | `^0.8` | `0.8.0` up to but not including `0.9.0` | `0.9.0` |
| `"0.0.3"` | `^0.0.3` | only `0.0.3` | `0.0.4` |
| `"=1.2.3"` | exact | only `1.2.3` | everything else |
| `">=1.2, <1.5"` | range | `1.2.0` up to but not including `1.5.0` | `1.5.0` |
| `"1.*"` | wildcard | any `1.x.y` | `2.0.0` |
Note the special case for 0.x versions. Before 1.0, a minor bump such as 0.8 to 0.9 is treated as a breaking change, so "0.8" will not move to 0.9.
Prefer the default caret form. Exact pins with = make it hard for Cargo to find one version that satisfies every crate in your tree.
Cargo.lock and reproducible builds
A requirement says which versions are acceptable. The Cargo.lock file records which version was actually chosen. The first build resolves requirements to concrete versions and writes them to Cargo.lock. Later builds reuse those versions, even when newer compatible ones exist.
The diagram shows the flow.
You change locked versions on purpose with cargo update:
cargo update # re-resolve everything within the requirements
cargo update -p rand # update only rand and what it needs
cargo tree # print the dependency tree
cargo tree -d # show crates that appear in more than one versionA common convention is to commit Cargo.lock for binaries and for workspaces whose output you ship. Library authors have historically left it out, because downstream users resolve their own versions. Current Cargo guidance is more relaxed, and committing it is also fine. What matters is that you decide deliberately.
Using a dependency in code
Dependencies are added to the extern prelude, so you can name them directly in paths. A crate name with a hyphen, such as serde-json, becomes an underscore in code, so it is serde_json.
use rand::Rng;
fn roll() -> u8 {
let mut rng = rand::thread_rng();
rng.gen_range(1..=6)
}
fn main() {
println!("rolled {}", roll());
}This example needs rand = "0.8" in [dependencies]. Without it, the compiler reports unresolved import rand.
If two crates collide on a name, or you want a shorter one, rename the dependency with package:
[dependencies]
json = { package = "serde_json", version = "1" }In code you then write json::to_string(...).
Other sources: path and Git
A path dependency is how workspace members use one another. It also works for a crate you are developing next to your main package.
[dependencies]
core = { path = "../core" }A Git dependency pulls from a repository:
[dependencies]
tool = { git = "https://github.com/example/tool", tag = "v1.4.0" }You can pin with tag, branch, or rev. Prefer tag or rev. A branch moves, so the locked commit changes whenever you run cargo update. Crates published to crates.io cannot depend on a Git-only or path-only crate. When you publish, a path dependency needs a version as well:
core = { path = "../core", version = "0.1.0" }Locally Cargo uses the path. In the published package it uses the version.
Dependency kinds
Cargo has three dependency tables, and each answers a different question.
| Table | Built for | Visible to |
|---|---|---|
| `[dependencies]` | normal builds | your library or binary code |
| `[dev-dependencies]` | tests, examples, benchmarks | test and example code only |
| `[build-dependencies]` | the `build.rs` script | `build.rs` only |
Putting a test-only crate in [dependencies] makes every user of your library compile it. Keep each crate in the narrowest table that works.
Common errors
Unresolved import. The code names a crate that is not in Cargo.toml. Add it with cargo add.
No matching package. Cargo cannot find a version that satisfies the requirement. Check the spelling and the version. A requirement like "2" fails if the crate has only released 1.x.
Version conflict. Two dependencies need incompatible requirements on a third crate that links native code, so only one copy may exist. Run cargo tree -i crate_name to see who requires it, then loosen your requirements or update the dependents.
Two versions of one crate. For pure Rust crates, Cargo can include both foo 0.8 and foo 0.9 in one build. This usually compiles, but types from the two versions are different types. You may see an error such as "expected foo::Rng, found a different foo::Rng". Use cargo tree -d to find the duplicate, and align your requirement with the version your other dependencies use.
Stale lock file after editing the manifest. If you change a requirement so that the locked version no longer fits, Cargo re-resolves just that crate on the next build. Passing --locked to a build turns this into an error, which is useful in CI because it catches a Cargo.lock that was not committed after a change.
Offline and vendored builds
cargo build --offline uses only crates already in the local cache. cargo vendor copies all dependency sources into a vendor/ directory so a build needs no network access. Both rely on Cargo.lock, which is another reason to keep it under version control for applications.
Exercise
Your Cargo.toml has rand = "0.8.4" and the registry contains rand 0.8.5, 0.9.0, and 1.0.0. Which version does Cargo choose on the first build, and what changes if you write rand = "=0.8.4" instead?
Show answer
With "0.8.4" (a caret requirement) Cargo accepts versions from 0.8.4 up to but not including 0.9.0, so it picks the newest in that range, 0.8.5, and records it in Cargo.lock. 0.9.0 is excluded because in 0.x versions a minor bump counts as breaking. With "=0.8.4" only 0.8.4 is accepted, so Cargo picks exactly that version.
Exercise
You are writing a library. A test uses the pretty_assertions crate to compare structs. Which table should it go in, and why does the choice matter to people who depend on your library?
Show answer
Put it in [dev-dependencies]. Dev-dependencies are built only for tests, examples, and benchmarks. If you put it in [dependencies], everyone who uses your library would have to download and compile it as well.