Sub topic 3
Adding and removing dependencies with cargo add and cargo remove
This chapter assumes you can create a project with cargo new, you know what a crate is, and you have read the [dependencies] table in Cargo.toml. Here you will use the cargo add and cargo remove commands to change that table from the terminal instead of editing it by hand.
What the commands do
cargo add and cargo remove are built into Cargo (since Rust 1.62). They edit the [dependencies] table, or its dev and build variants, in your Cargo.toml. They do not compile anything.
cargo add does three things:
- It looks up the crate in the registry index, which is crates.io unless you configure another.
- It picks a version, or uses the one you asked for.
- It writes a dependency entry into the manifest.
The commands edit the file in place, so your comments, ordering, and formatting stay as they were. Editing the file by hand gives the same result. The commands save you from typos in crate names and from looking up the current version.
Adding your first dependencies
Create a project and add two crates:
cargo new json_demo
cd json_demo
cargo add serde --features derive
cargo add serde_jsonCargo prints what it changed. The output looks like this, though the version numbers and feature list depend on the release:
Updating crates.io index
Adding serde v1.0.219 to dependencies
Features:
+ derive
+ serde_derive
+ std
- alloc
- rc
- unstableA + marks a feature that is now enabled. A - marks one that exists but is off. This list is a quick way to discover which features a crate offers.
The manifest now contains the following table:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"Which version string appears depends on your Cargo version. Older releases write the full release number, such as "1.0.219". Newer releases may write a shorter requirement such as "1". Both are caret requirements, meaning "compatible with this 1.x release". The next chapter covers how they differ.
The serde entry uses the table form because it has a feature list. The serde_json entry uses the short form because it has only a version.
Using the crate in code
After the manifest changes, the crate is available to your code under its library name. Replace src/main.rs with:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
let json = serde_json::to_string(&p).unwrap();
println!("{json}");
let back: Point = serde_json::from_str(&json).unwrap();
println!("{back:?}");
}cargo run downloads the crates, compiles them, and prints:
{"x":1,"y":2}
Point { x: 1, y: 2 }If you had skipped --features derive, the #[derive(Serialize, Deserialize)] line would fail to compile. The derive macros live behind the derive feature of serde.
Choosing the version
With no version, cargo add takes the newest release it considers suitable. It skips yanked releases. It also skips pre-releases such as 2.0.0-beta.1 unless you ask for one.
Recent Cargo versions also respect the rust-version field in your Cargo.toml. They prefer a release whose minimum supported Rust version fits your project. Pass --ignore-rust-version to override that.
To choose the version yourself, add @ and a requirement after the name:
cargo add [email protected]
cargo add [email protected]
cargo add anyhow@=1.0.80
cargo add clap@4 --features deriveThe text after @ is written to the manifest as a version requirement. [email protected] means ^1.10. anyhow@=1.0.80 pins exactly that release. If no release satisfies the requirement, the command fails and leaves the manifest unchanged.
Common options
| Option | Effect |
|---|---|
| `-F`, `--features a,b` | Enable features. Separate names with commas or spaces. |
| `--no-default-features` | Turn off the crate's default features. |
| `--default-features` | Turn default features back on for an existing entry. |
| `--optional` | Mark the dependency as optional. |
| `--rename NAME` | Use `NAME` as the key in your manifest, and write `package = "..."`. |
| `--dev`, `-D` | Add to `[dev-dependencies]`. |
| `--build` | Add to `[build-dependencies]`. |
| `--target TRIPLE` | Add to a target-specific table. |
| `--git URL`, `--path DIR` | Use a git repository or a local directory instead of crates.io. |
| `-p`, `--package NAME` | Pick a workspace member to edit. |
| `--dry-run` | Show the change without writing the file. |
| `--offline`, `--locked` | Use only the local cache, or refuse to change `Cargo.lock`. |
You can add several crates in one command, but features then apply to each one named. Run the commands separately when the features differ:
cargo add tokio --no-default-features --features rt,macros
cargo add log env_loggerThe first command produces this entry:
tokio = { version = "1", default-features = false, features = ["rt", "macros"] }Previewing with --dry-run
--dry-run prints what would change and exits without writing the manifest:
cargo add reqwest --features json --dry-runUse it to check a crate's feature list before you commit to it. The command still contacts the registry, so it needs network access unless you pass --offline.
Running cargo add on an existing dependency
If the crate is already in the manifest, cargo add updates the entry instead of adding a second one. Features you request are merged with the features already listed. Run this on the project above:
cargo add serde --features rcThe serde entry now lists both derive and rc. Features are never removed by cargo add unless you use --no-default-features to change the default-features setting.
If you give a new version, as in cargo add [email protected], the requirement in the manifest is replaced.
This behavior makes the command safe to repeat. It also means you cannot use cargo add to remove a single feature. For that, edit the features array by hand.
Dev, build, and target-specific dependencies
The kind of table is chosen with a flag, and the same crate can appear in more than one table:
cargo add --dev pretty_assertions
cargo add --build cc
cargo add --target 'cfg(windows)' windows-sysThe first two commands write to [dev-dependencies] and [build-dependencies]. The third writes to a table named [target.'cfg(windows)'.dependencies]. Quote the --target value so your shell does not interpret the parentheses. Chapter 8 explains when each table is used.
Removing dependencies
cargo remove is the reverse operation. It deletes the entry from the manifest:
cargo remove serde_jsonCargo prints a line such as Removing serde_json from dependencies. It does the following:
- It looks in
[dependencies]by default. Use--devor--buildto target the other tables. - It cleans up references in the
[features]table. If a feature listeddep:serde_jsonorserde_json/something, that reference is removed. If the table ends up empty, Cargo removes it. - It accepts several names at once, such as
cargo remove log env_logger. - It supports
--dry-run,-p, and--targetlikecargo add.
If a crate sits in two tables, say [dependencies] and [dev-dependencies], cargo remove name removes only the entry from [dependencies]. Run cargo remove --dev name to remove the other.
After a removal, your code may still contain use serde_json::... lines. Cargo does not edit source files, so the next cargo build fails with an unresolved import until you remove them.
What the commands do not do
Knowing the limits avoids confusion:
cargo adddoes not compile or download the crate's source. It reads only the index. The download happens at the next build or atcargo fetch.- It does not edit
Cargo.lockitself. The lock file changes when Cargo next resolves dependencies, usually oncargo build,cargo check, orcargo run. - It does not edit your Rust source. You still write
usestatements yourself. - It does not check that the crate is a good choice. A misspelled name can match a different, real crate, so verify the name against its crates.io page.
Common errors
| Error | Cause and fix |
|---|---|
| `could not find 'name' in registry` | The name is misspelled, or the crate does not exist. Check the spelling. |
| `unrecognized subcommand 'add'` | Your Cargo is older than 1.62. Run `rustup update`. |
| `the crate 'x' does not have these features: y` | The feature name is wrong. Run `cargo add x --dry-run` to list valid features. |
| `could not find Cargo.toml` | You are outside a Cargo project. Change into the project directory. |
| `unresolved import` after a build | You added the crate under the wrong name. Use the library name, which replaces hyphens with underscores. |
| `no matching package named x found` with `--offline` | The crate is not in the local cache. Remove `--offline`. |
The last row of the table is worth a closer look at hyphens. A crate named serde-json-core on crates.io is imported in code as serde_json_core. Cargo accepts either spelling in cargo add, but Rust code only accepts the underscore form.
Command line or manual editing
Either works, and they produce the same file. Use cargo add for everyday additions because it checks the name and version against the registry. Edit by hand when you need something the flags do not cover. Examples are removing a single feature, adding a comment, or arranging several entries in the dotted-table form.
You can mix the two. A common habit is to run cargo add for new crates and then open the manifest to tidy up.
Exercise
You run cargo add tokio --no-default-features --features rt,macros, then later run cargo add tokio --features time. What features does the tokio entry have afterward, and does the second command re-enable the default features?
Show answer
The entry has rt, macros, and time enabled. Features are merged into the existing entry. The second command does not re-enable default features, because default-features = false stays in place until you pass --default-features.
Exercise
You add a crate with cargo add --dev insta and later decide it is no longer needed. Which command removes it, and why does cargo remove insta alone fail or do nothing useful?
Show answer
Run cargo remove --dev insta. Without --dev, cargo remove looks only in [dependencies], where the crate is not listed, so it reports that it cannot find the dependency there.