Sub topic 9
Adding a Dependency from crates.io
This chapter assumes you can run cargo new, cargo build, and cargo run, and that you have read the Cargo.toml manifest at least once. You will add a crate from crates.io to a project, learn how Cargo records what it chose, and learn how to diagnose the errors that come up most often.
What a dependency is in Cargo
A crate is a unit of Rust compilation and distribution. A library crate offers code that other crates can call. A dependency is a library crate that your project uses. crates.io is the default public registry where people publish crates. When you ask Cargo for a dependency, it does four things:
- It reads the version requirement in
Cargo.toml. - It resolves a concrete version that satisfies that requirement, along with the versions of everything that crate needs in turn (its transitive dependencies).
- It downloads and compiles those crates.
- It records the exact versions it chose in
Cargo.lock.
The manifest says what you are willing to accept. The lock file says what you actually got.
Adding a crate with cargo add
The cargo add command edits Cargo.toml for you. It looks up the latest compatible release on crates.io and inserts it into the [dependencies] table. Run it from inside a project directory:
cargo add randCargo prints a line such as Adding rand v0.8.5 to dependencies and lists the crate's feature flags. The version number you see depends on when you run the command. Open Cargo.toml and you will find a new entry:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"Nothing has been downloaded yet. cargo add only changes the manifest (and it may query the registry index to pick a version). The download happens on the next command that needs the crate, such as cargo build, cargo check, or cargo run.
Editing the manifest by hand
cargo add is a convenience. You can type the same line into [dependencies] yourself, and Cargo will treat it identically. Hand editing is useful when you want to paste a snippet from a crate's documentation or to change several entries at once. A mistake in a hand edit, such as a misspelled crate name, shows up the next time Cargo reads the manifest.
Using the dependency in code
Adding a crate does not import anything into your source files. You still name the items you want with use. This program picks a random number between 1 and 6:
use rand::Rng;
fn main() {
let roll: u8 = rand::thread_rng().gen_range(1..=6);
println!("You rolled a {roll}");
}Run it with cargo run. On the first run, Cargo downloads rand and the crates it depends on, compiles them, and then compiles your program. You will see lines such as Downloaded, Compiling, and finally Running. Later runs skip the dependency compilation, because the compiled output is cached in target/.
The example uses the rand 0.8 API. Newer major versions of rand renamed some functions (for example, thread_rng became rng in 0.9). If cargo add rand selects a newer major version than 0.8, the program above may fail to compile. In that case, either read the documentation for the version you got, or request the older line explicitly with cargo add [email protected].
Version requirements and semantic versioning
The string "0.8.5" in Cargo.toml is not a pin to exactly that version. It is a caret requirement, which is the default. Cargo reads "0.8.5" as "any version at least 0.8.5 and below 0.9.0". Cargo follows semantic versioning (SemVer) as it is used in the Rust ecosystem: a change in the leftmost non-zero number signals a breaking change.
| Requirement | Meaning | Allowed range |
|---|---|---|
| `"1.2.3"` | Caret (default) | `>=1.2.3, <2.0.0` |
| `"0.8.5"` | Caret, leftmost non-zero is the minor number | `>=0.8.5, <0.9.0` |
| `"0.0.3"` | Caret, leftmost non-zero is the patch number | `>=0.0.3, <0.0.4` |
| `"~1.2.3"` | Tilde | `>=1.2.3, <1.3.0` |
| `"1.*"` | Wildcard | `>=1.0.0, <2.0.0` |
| `"=1.2.3"` | Exact | exactly `1.2.3` |
| `">=1.2, <1.5"` | Comma-separated range | `>=1.2.0, <1.5.0` |
Use the default unless you have a reason not to. Exact pins (=) make it hard for Cargo to find versions that satisfy every crate in your dependency graph, because other crates may need a different patch release of the same crate.
Cargo.lock and reproducible builds
The first time Cargo resolves your dependencies, it writes Cargo.lock next to Cargo.toml. This file lists every crate in the graph with its exact version and a checksum. You should not edit it by hand. Cargo maintains it.
On later builds, Cargo reuses the locked versions even if newer compatible releases exist. This is what makes builds repeatable: two machines that share the same Cargo.lock compile the same versions.
To move to newer versions that still satisfy your requirements, run:
cargo updateThis rewrites Cargo.lock with the newest versions that Cargo.toml allows. To update only one crate, name it:
cargo update randRaising a requirement beyond what Cargo.toml allows, such as moving from 0.8 to 0.9, is a different operation. You change the manifest (with cargo add [email protected] or by editing the line), and Cargo updates the lock file when it next builds.
Should Cargo.lock be committed?
The usual guidance is to commit Cargo.lock for projects that produce executables, so every build uses the same versions. For libraries that other projects will depend on, the lock file has less effect, because a downstream project uses its own lock file. Many teams commit it for both. Decide by whether you need repeatable builds of that repository.
Features, dev-dependencies, and build-dependencies
Many crates have optional functionality that is turned on by features. A feature is a named flag that includes extra code when it is enabled. You can enable one with cargo add:
cargo add serde --features deriveThis produces a table-style entry in the manifest:
[dependencies]
serde = { version = "1", features = ["derive"] }The inline table form is how you attach options to a dependency. Other common options are default-features = false to turn off a crate's default feature set, and optional = true to make the dependency conditional on one of your own features.
Not every dependency belongs in the final program. Cargo has separate tables for other roles:
| Table | Used for | Added with |
|---|---|---|
| `[dependencies]` | Code your program or library needs at run time | `cargo add name` |
| `[dev-dependencies]` | Code needed only for tests, examples, and benchmarks | `cargo add --dev name` |
| `[build-dependencies]` | Code needed by a `build.rs` build script | `cargo add --build name` |
Keeping test-only crates in [dev-dependencies] means they are not compiled into your released binary and are not imposed on users of your library.
Removing a dependency and inspecting the graph
To remove a crate, run:
cargo remove randThis deletes the entry from Cargo.toml. Remember to delete the use lines that referred to it, or the build will fail with an unresolved import.
To see what ended up in your build, including transitive dependencies, use:
cargo treeThe output is an indented tree. A crate that appears under several parents is listed under each, and cargo tree -d shows crates that appear in more than one version. Seeing two versions of the same crate is normal when different dependencies require incompatible SemVer ranges, but it increases compile time and binary size.
Other sources of dependencies
crates.io is the default, but a dependency can come from elsewhere. These forms are written in Cargo.toml:
[dependencies]
# A crate in a folder on your machine
my_helpers = { path = "../my_helpers" }
# A crate from a Git repository
some_crate = { git = "https://github.com/example/some_crate" }Path dependencies are common when you split one project into several crates. Git dependencies are useful for trying an unreleased fix, but they cannot be published to crates.io as they are. When you publish a crate, every dependency must have a version that crates.io knows about.
Common errors and how to read them
| Message (abbreviated) | Likely cause | Fix |
|---|---|---|
| `no matching package named 'x' found` | Misspelled crate name, or the name does not exist in the registry | Check the spelling on crates.io |
| `failed to select a version for the requirement` | The requirement matches no published version | Loosen the requirement or pick an existing version |
| `failed to select a version for 'x'` with conflicting requirements | Two dependencies need incompatible versions of a crate that can only appear once, such as a crate that links a native library | Align versions, or update the crates involved |
| `unresolved import` or `use of undeclared crate or module` | The crate is not in `Cargo.toml`, or you removed it, or the name is spelled differently in code | Add it, and use the crate name with hyphens replaced by underscores |
| `unable to update registry` or network errors | No internet access, a proxy, or a firewall | Check connectivity and proxy settings |
| `error[E0432]` or `E0599` right after a version bump | The API changed in the new version | Read the changelog, or return to the previous version |
A detail that causes confusion: a crate published as serde-jsonstyle hyphenated names is referenced in code with underscores. For example, the crate rand_core has an underscore in both places, but a crate named my-crate is used as my_crate in use statements.
Working offline
After a crate has been downloaded once, it sits in Cargo's local cache. If you have no network, cargo build --offline tells Cargo to use only what is cached and to fail rather than try to reach the registry. This works only if the cache already contains versions that satisfy your lock file.
Exercises
Exercise
You run cargo add rand and then open Cargo.toml. It contains rand = "0.8.5". Which versions of rand may Cargo choose on a later cargo update, and which will it never choose without a manifest change?
Show answer
Cargo may choose any version from 0.8.5 up to, but not including, 0.9.0, for example 0.8.6. It will not choose 0.9.0 or later, because with a leading zero the minor number marks a breaking change. To move to 0.9, you must change the requirement in Cargo.toml, for example with cargo add [email protected].
Exercise
A teammate clones your executable project and gets different dependency versions than you do. Which file is likely missing from the repository, and what should you do?
Show answer
Cargo.lock is missing. For a project that produces an executable, commit Cargo.lock so every build resolves the same exact versions.
Exercise
You want a crate called pretty_assertions available only in your tests. Write the command that adds it, and name the manifest table it will appear in.
Show answer
Run cargo add --dev pretty_assertions. The entry appears in the [dev-dependencies] table.