Add dependencies by listing them under the [dependencies] section in your Cargo.toml file, specifying the crate name and version, then run cargo build or cargo update to fetch them. You can also use cargo add to automate this process directly from the command line.
The manual approach involves editing Cargo.toml to include the crate name and a version constraint. Cargo uses semantic versioning, so 1.2 matches any 1.2.x release, while =1.2.3 locks to that exact version.
[dependencies]
# Simple version constraint (matches 1.2.0, 1.2.1, etc.)
serde = "1.0"
# Exact version
tokio = "=1.35.0"
# With optional features
reqwest = { version = "0.11", features = ["json", "blocking"] }
For a faster workflow, use the cargo add command, which automatically updates Cargo.toml and downloads the crate. This is the preferred method for most day-to-day work as it prevents syntax errors and handles version resolution immediately.
# Add a crate with the latest compatible version
cargo add serde
# Add a specific version
cargo add tokio@1.35.0
# Add with specific features
cargo add reqwest --features json,blocking
If you need a dependency only for tests or benchmarks, place it under [dev-dependencies] or [build-dependencies] respectively. This ensures they aren't compiled into your production binary.
[dev-dependencies]
criterion = "0.5"
[build-dependencies]
cc = "1.0"
After modifying Cargo.toml, run cargo build to compile your project with the new dependencies. If you encounter version conflicts, cargo update can help refresh the Cargo.lock file to resolve them. Always check the official crate documentation on crates.io for the correct version syntax and available features before adding.