Sub topic 3
Adding and removing dependencies with cargo add and cargo remove
This chapter assumes you have Rust and Cargo installed, can create a project with cargo new, and know that dependencies live in the [dependencies] table of Cargo.toml. You will use cargo add and cargo remove to change that table from the command line instead of editing it by hand.
What the commands do
cargo add looks up a crate on crates.io, picks a version, and writes an entry into your Cargo.toml. cargo remove deletes an entry. Both commands edit the file in place and keep your existing comments and formatting. Editing the file by hand gives the same result, so use whichever you prefer.
Adding your first dependencies
Create a project and add two crates. serde needs its derive feature so that #[derive(Serialize, Deserialize)] works.
cargo new json_demo
cd json_demo
cargo add serde --features derive
cargo add serde_jsonCargo prints a line for each change. It also lists the features of the crate and marks which ones are enabled. Your Cargo.toml now contains this table:
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"The version "1" is a caret requirement. It allows any release compatible with 1.x.y. The next chapter covers the exact rules.
cargo add writes the major version, or the leading non-zero part of the version, and not the full number you might expect. If the latest serde_json is 1.0.140, the file still says "1". The exact release that Cargo picks is recorded in Cargo.lock.
Checking it works
Put this program in src/main.rs. It serializes a struct to JSON text and parses the text back.
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:?}");
}Run cargo run. The output is:
{"x":1,"y":2}
Point { x: 1, y: 2 }Useful options
| Command | Effect |
|---|---|
| `cargo add [email protected]` | Asks for a specific version requirement |
| `cargo add serde --features derive` | Enables a feature |
| `cargo add tokio --no-default-features` | Turns off the default features |
| `cargo add --dev pretty_assertions` | Adds to `[dev-dependencies]` |
| `cargo add --build cc` | Adds to `[build-dependencies]` |
| `cargo add --dry-run serde` | Shows the change without writing it |
Use --dry-run when you are unsure what a command will do.
cargo add --dev pretty_assertions
cargo add --build cc
cargo remove serde_jsonRemoving a dependency
cargo remove serde_json deletes the serde_json line from [dependencies]. If the crate was in another table, name the table with --dev or --build, as in cargo remove --dev pretty_assertions.
After a removal your code may fail to compile, because use serde_json no longer resolves. Cargo does not check your source files. You need to delete or change those uses yourself. The next cargo build also drops the crate from Cargo.lock.
Common errors
- "could not find ... in registry": The crate name is misspelled, or the crate does not exist. Check the name on crates.io. Hyphens and underscores both appear in crate names, so copy the name exactly.
- "unrecognized feature": The feature name does not exist for that crate.
cargo addlists the available features when you add the crate. - "cannot find
serde_jsonin the list of dependencies": You rancargo removefor a crate that is not in that table. Check whether it is a dev or build dependency. - Compile error after adding a crate: In Rust code, use the crate name with hyphens turned into underscores. The crate
serde-jsonwould be writtenserde_json.
Exercise
You run cargo add serde and then write #[derive(Serialize)] in your code, but the compiler reports that it cannot find the derive macro. What did you forget, and what command fixes it?
Show answer
The derive feature of serde is not enabled by default. Run cargo add serde --features derive, which changes the entry to serde = { version = "1", features = ["derive"] }.
Exercise
What does cargo remove serde_json leave unchanged in your project?
Show answer
It leaves your Rust source files unchanged. Any serde_json calls in the code will fail to compile until you remove or replace them.