Sub topic 2
Declaring dependencies in Cargo.toml
This chapter assumes you can create a project with cargo new, read basic Rust syntax and use paths, and run commands in a terminal. You don't need to know how version requirements work in detail. The next chapters cover cargo add and SemVer. Here you learn what a dependency declaration is and how Cargo reads it.
The manifest is the source of truth
Cargo.toml is your project's manifest. It is written in TOML, a plain-text format of key = value pairs grouped under [table] headers. When you build, Cargo reads the manifest to decide which crates to fetch, which versions are acceptable, and which options to turn on.
A crate is a unit of Rust code that can be compiled and shared. Every dependency you declare names a crate. Unless you say otherwise, Cargo looks for that crate on crates.io, the default public registry.
Here is the flow from declaration to compiled program.
Resolution is the step where Cargo picks one concrete version for each crate, so that every requirement in the whole dependency graph is satisfied. You declare ranges, and Cargo chooses the versions.
The [dependencies] table
Each entry in [dependencies] maps a dependency name to a description of what you need. A complete manifest looks like this:
[package]
name = "json_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"The key on the left, such as serde_json, is the name of the crate on crates.io. The value on the right says which versions you accept and how to build the crate.
The string "1" is a version requirement. It does not mean "exactly 1". Cargo reads it as a caret requirement, meaning any version compatible with 1.x.y. The SemVer chapter explains the exact rules. For now, remember that a bare version string allows compatible upgrades and never allows a new major version.
Three ways to write the same dependency
TOML lets you express one dependency in several equivalent shapes. You will see all of them in real projects.
[dependencies]
# 1. Short form: just a version requirement
regex = "1"
# 2. Inline table: version plus other keys on one line
serde = { version = "1", features = ["derive"] }
# 3. Dedicated table: the same idea, spread over several lines
[dependencies.chrono]
version = "0.4"
default-features = false
features = ["clock"]All three forms are valid together in one file. Choose by readability:
- Use the short form when a version is all you need.
- Use the inline table when you have one or two extra keys.
- Use the dedicated table when a dependency has many keys, so each one gets its own line.
One caution about the dedicated form. A [dependencies.chrono] header starts a new table, so every key after it belongs to chrono until the next header. Put these entries last, or you may attach other keys to the wrong dependency.
Keys you can set on a dependency
The short string form supports only a version. The table forms accept these keys:
| Key | Meaning |
|---|---|
| `version` | The SemVer requirement for the crate. |
| `features` | A list of optional crate features to enable. |
| `default-features` | Set to `false` to turn off the crate's default feature set. |
| `optional` | If `true`, the dependency is only built when a feature of your crate enables it. |
| `package` | The real crates.io name, used when you rename the dependency locally. |
| `path` | A local directory containing the crate. |
| `git` | A git repository URL containing the crate. |
| `workspace` | If `true`, inherit the declaration from the workspace root. |
Later chapters cover features, renaming, and workspaces in detail. This chapter only needs you to recognize that these keys live in the same place as version.
Two keys deserve a note now:
- A dependency with a
pathorgitkey is not fetched from crates.io. If you also give aversionwithpath, Cargo uses the local path while you develop and uses the version when you publish your own crate. - Cargo requires a
versionfor any crates.io dependency in a crate you publish. A dependency with onlygitorpathcannot be published.
Names: Cargo.toml versus Rust code
The dependency name in Cargo.toml and the name you write in Rust source are usually the same, with one exception. Crate names may contain hyphens, but Rust identifiers cannot. Cargo converts hyphens to underscores when it hands the crate to the compiler.
[dependencies]
tracing-subscriber = "0.3"In code, you refer to it with an underscore:
use tracing_subscriber::fmt;
fn main() {
fmt::init();
println!("subscriber installed");
}If you write use tracing-subscriber::fmt;, the compiler reports a syntax error, not a missing crate. This catches many newcomers.
A complete working example
This project declares one dependency and uses it. Create it with cargo new regex_demo, then set Cargo.toml to:
[package]
name = "regex_demo"
version = "0.1.0"
edition = "2021"
[dependencies]
regex = "1"Put this in src/main.rs:
use regex::Regex;
fn main() {
let re = Regex::new(r"\d+").unwrap();
let text = "order 66, aisle 12, shelf 7";
for m in re.find_iter(text) {
println!("found {} at {}..{}", m.as_str(), m.start(), m.end());
}
}Run cargo run. On the first build Cargo prints lines such as Updating crates.io index and Downloading crates ..., then compiles regex and its own dependencies before compiling your crate. The program prints:
found 66 at 6..8
found 12 at 16..18
found 7 at 26..27Run cargo run a second time and the download and dependency compilation steps disappear. The sources are cached in your Cargo home directory (~/.cargo by default), and compiled dependencies are cached in target/.
What Cargo does when the manifest changes
Editing Cargo.toml by hand is a normal way to add a dependency. After you save, the next cargo build, cargo check, or cargo run does the following:
- Parses the manifest and checks that it is valid TOML with known keys.
- Compares your requirements with the versions recorded in
Cargo.lock, if the file exists. - Keeps locked versions that still satisfy your requirements.
- Resolves and records new versions only for entries that are new or whose requirement no longer matches.
This means adding one dependency does not silently upgrade the others. Existing locked versions stay put unless the manifest forces a change. The lock file has its own chapter.
Common errors
Most problems at this stage come from a small set of mistakes.
- Misspelled crate name. Cargo reports that no matching package named your misspelling was found in the registry. It often suggests similar names. Check the spelling on crates.io.
- Requirement with no matching version. Writing
serde = "2"fails because no 2.x release of serde exists. Cargo reports that it failed to select a version for the requirement. Loosen or correct the requirement. - Duplicate key. Declaring
serdetwice in the same table, or once under[dependencies]and again under[dependencies.serde], is a TOML error. Keep one entry per dependency name. - Wrong table. A dependency placed under
[package]or after an unrelated header is ignored or rejected. Confirm that the entry sits under[dependencies]. - Features not enabled. If
#[derive(Serialize)]produces an error saying the macro cannot be found, you probably left outfeatures = ["derive"]onserde. - Hyphen in a
usepath. As shown above, replace hyphens with underscores in Rust code.
Checking what you declared
You rarely need to guess what Cargo understood from your manifest. Two commands show you:
cargo metadata --format-version 1 --no-deps
cargo tree --depth 1The first prints your package information as JSON, including the dependencies Cargo parsed. The second lists your direct dependencies with the versions Cargo picked. Compare these with your intent when a build behaves unexpectedly.
Exercise
A project's Cargo.toml contains tracing-subscriber = "0.3" under [dependencies]. Your code says use tracing-subscriber::fmt; and fails to compile. What is wrong, and what is the fix?
Show answer
Rust identifiers cannot contain hyphens, so the path is a syntax error. Cargo exposes the crate to the compiler with hyphens replaced by underscores. Write use tracing_subscriber::fmt;. The name in Cargo.toml stays with the hyphen.
Exercise
You write serde = { version = "1", features = ["derive"] } under [dependencies], then later add a separate [dependencies.serde] table with version = "1". What happens, and how should you fix it?
Show answer
Cargo reports an error because the key serde is defined twice in the same table. Keep a single entry for serde, either as the inline table or as the dedicated table, and put the features key in that one entry.