Sub topic 3
Dev, build and target-specific dependencies
Assume you know basic Rust syntax, can create a project with cargo new, and can run Cargo commands in a terminal. This chapter focuses on dependencies needed in different parts of a project.
Separate dependencies by purpose
A normal dependency is used by the library or binary you publish. A dev-dependency is used only by tests, examples, and benchmarks. A build-dependency is used by a build.rs build script.
Target-specific dependencies apply only on a selected operating system or architecture.
[dependencies]
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
pretty_assertions = "1"
[build-dependencies]
cc = "1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = ["Win32_System_Console"] }Use commands instead of editing the manifest manually when convenient:
cargo add --dev pretty_assertions
cargo add --build cc
cargo testCargo does not compile a dev-dependency for a normal release build unless something else requires it.
Update dependencies safely
Cargo.toml states allowed versions, while Cargo.lock records the exact resolved versions. Review changes before updating:
cargo update -p serde
cargo test
cargo treeUpdate one package when possible. A broad update can change many transitive dependencies, so inspect the lockfile diff and run the complete test suite.
Inspect the dependency tree
cargo tree shows direct and transitive dependencies. These commands help locate duplication and feature sources:
cargo tree
cargo tree -i serde
cargo tree -e featuresThe -i option shows which packages depend on a selected crate. This is useful when a vulnerable or duplicated package appears indirectly.
Evaluate a crate first
Before adding a crate, check its documentation, license, maintenance activity, recent releases, dependency count, and enabled default features. Prefer a focused, maintained crate with a license compatible with your project. Read its feature list before accepting large optional components.
Use alternative sources
A dependency can come from a local path or Git repository. A renamed dependency lets two versions of the same package use different names:
[dependencies]
rand07 = { package = "rand", version = "0.7" }
my_local = { path = "../my_local" }
my_fork = { git = "https://github.com/example/my_fork" }Git and path dependencies are useful during development, but published libraries should avoid machine-specific paths.
Share versions in a workspace
A workspace centralizes dependency requirements:
[workspace]
members = ["app", "util"]
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }A member then inherits the declaration:
[dependencies]
serde = { workspace = true }Exercise
Where should a crate used only by integration tests be declared, and which command inspects why another crate is present?
Show answer
Declare it under [dev-dependencies]. Run cargo tree -i crate_name to inspect reverse dependencies.