How to Add Dependencies to a Rust Project

Add dependencies to your Rust project by listing them in the `[dependencies]` section of your `Cargo.toml` file or by running the `cargo add` command.

Add dependencies to your Rust project by listing them in the [dependencies] section of your Cargo.toml file or by running the cargo add command. Cargo will then automatically download, compile, and link the specified crates for your project.

The most modern and efficient approach is using the cargo add command, which handles updating the manifest and lockfile for you. For example, to add the popular serde crate with JSON support:

cargo add serde --features derive

This command automatically appends the correct version and feature flags to your Cargo.toml. If you prefer manual control or need to specify complex configurations, edit Cargo.toml directly. Here is a typical configuration block:

[dependencies]
# Simple version specification
tokio = "1.35"

# Specific version with features
serde = { version = "1.0", features = ["derive"] }

# Git dependency (useful for unreleased code)
my-custom-lib = { git = "https://github.com/example/repo", branch = "main" }

After modifying Cargo.toml manually, run cargo build or cargo check to fetch and compile the new dependencies. Cargo resolves the dependency tree, ensuring all transitive dependencies are met, and stores the exact resolved versions in Cargo.lock to guarantee reproducible builds across different environments.

If you need to update an existing dependency to its latest compatible version, use cargo update. For example, cargo update serde will fetch the newest version of serde that satisfies the version constraint in your Cargo.toml. To remove a dependency, you can either manually delete the line from Cargo.toml or use cargo remove <package-name>. Always commit your Cargo.lock file to version control to ensure your team and CI pipelines build with the exact same dependency versions.