Cargo helps you add and manage external code libraries (called dependencies) easily in your Rust projects.
0
0
Cargo dependency management in Rust
Introduction
When you want to use code someone else wrote to save time.
When your project needs extra features not in Rust's standard library.
When you want to keep your project organized with clear versions of libraries.
When you want Cargo to automatically download and update libraries for you.
Syntax
Rust
[dependencies] crate_name = "version" # Example: serde = "1.0"
Dependencies are listed in the Cargo.toml file under the [dependencies] section.
The version uses quotes and usually follows semantic versioning like "1.0" or "^1.0".
Examples
Adds the
rand crate version 0.8 as a dependency.Rust
[dependencies]
rand = "0.8"Adds
serde with the derive feature enabled.Rust
[dependencies]
serde = { version = "1.0", features = ["derive"] }Uses any
regex version compatible with 1.5 (like 1.5.3, 1.6, etc.).Rust
[dependencies]
regex = "^1.5"Sample Program
This program uses the rand crate to generate a random number between 1 and 10. The dependency is declared in Cargo.toml under [dependencies]. Cargo downloads and manages the rand crate automatically.
Rust
[package] name = "hello_cargo" version = "0.1.0" edition = "2021" [dependencies] rand = "0.8" // src/main.rs use rand::Rng; fn main() { let mut rng = rand::thread_rng(); let n: u8 = rng.gen_range(1..=10); println!("Random number between 1 and 10: {}", n); }
OutputSuccess
Important Notes
Run cargo build or cargo run to let Cargo download and compile dependencies.
You can update dependencies with cargo update.
Use exact versions or version ranges to control updates.
Summary
Cargo manages external libraries by listing them in Cargo.toml.
Dependencies help you reuse code and add features easily.
Cargo downloads, compiles, and updates dependencies automatically.