Rust Cargo
Rust's build system and package manager
๐ฆ What is Cargo?
Cargo is Rust's built-in package manager and build system. It handles project creation, dependency management, compilation, testing, and publishing packages to make Rust development seamless and efficient.
# Create a new Rust project
cargo new my_project
cd my_project
cargo run
Essential Cargo Commands
cargo new
Create a new Rust project
cargo new hello_world
cargo new --lib my_library
cargo build
Compile the project
cargo build
cargo build --release
cargo run
Build and run the project
cargo run
cargo run --bin my_binary
cargo test
Run project tests
cargo test
cargo test test_name
๐น Cargo.toml Configuration
The Cargo.toml file contains project metadata and dependencies:
[package]
name = "my_project"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <[email protected]>"]
description = "A sample Rust project"
license = "MIT"
[dependencies]
serde = "1.0"
tokio = { version = "1.0", features = ["full"] }
rand = "0.8"
[dev-dependencies]
assert_cmd = "2.0"
[[bin]]
name = "my_binary"
path = "src/bin/main.rs"
Key sections:
- [package]: Project metadata
- [dependencies]: Runtime dependencies
- [dev-dependencies]: Development-only dependencies
- [[bin]]: Binary target configuration
๐น Managing Dependencies
Add and manage external crates easily:
# Add a dependency
cargo add serde
cargo add tokio --features full
# Remove a dependency
cargo remove serde
# Update dependencies
cargo update
cargo update serde
๐ธ Using Dependencies in Code
// Cargo.toml: serde = { version = "1.0", features = ["derive"] }
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: "Alice".to_string(),
age: 30,
};
let json = serde_json::to_string(&person).unwrap();
println!("JSON: {}", json);
}
๐น Project Structure
Cargo follows a standard project layout:
my_project/
โโโ Cargo.toml # Project configuration
โโโ Cargo.lock # Dependency lock file
โโโ src/ # Source code
โ โโโ main.rs # Binary entry point
โ โโโ lib.rs # Library entry point
โ โโโ bin/ # Additional binaries
โ โโโ helper.rs
โโโ tests/ # Integration tests
โ โโโ integration_test.rs
โโโ benches/ # Benchmarks
โ โโโ my_benchmark.rs
โโโ examples/ # Example code
โโโ example.rs
Directory purposes:
- src/: Main source code
- tests/: Integration tests
- benches/: Performance benchmarks
- examples/: Usage examples
๐น Build Profiles
Customize compilation settings for different scenarios:
[profile.dev]
opt-level = 0 # No optimization
debug = true # Include debug info
panic = "unwind" # Unwind on panic
[profile.release]
opt-level = 3 # Maximum optimization
debug = false # No debug info
lto = true # Link-time optimization
codegen-units = 1 # Single codegen unit
# Build with different profiles
cargo build # Uses dev profile
cargo build --release # Uses release profile
cargo run --release # Run optimized build