Cargo in Rust (Advanced)
In this lesson, you will explore advanced features of Cargo, Rust’s build system and package manager. Cargo does much more than just build and run code.
Advanced Cargo knowledge helps you manage large projects, multiple crates, dependencies, build profiles, and workspaces efficiently.
What Is Cargo?
Cargo is the official tool used to manage Rust projects. It handles:
- Building and compiling code
- Dependency management
- Project structure
- Testing and benchmarking
Every professional Rust project relies heavily on Cargo.
Common Cargo Commands
Before moving into advanced topics, let’s review important Cargo commands.
cargo new my_project
cargo build
cargo run
cargo check
cargo test
Each command serves a specific purpose during development.
Cargo Build Profiles
Cargo supports different build profiles that control how your code is compiled.
The two main profiles are:
- dev – optimized for fast compilation
- release – optimized for performance
cargo build --release
Release builds produce faster executables but take longer to compile.
Customizing Profiles in Cargo.toml
You can customize how Cargo builds your project by editing Cargo.toml.
[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
This allows fine-grained control over performance and debugging.
Dependency Features
Many crates provide optional features that can be enabled or disabled.
This reduces binary size and improves performance.
[dependencies]
serde = { version = "1.0", features = ["derive"] }
Only the required functionality is included in your build.
Optional Dependencies
Some dependencies can be marked as optional.
[dependencies]
log = { version = "0.4", optional = true }
Optional dependencies are enabled through features.
Cargo Workspaces
A workspace allows you to manage multiple related crates in a single project.
Workspaces share dependencies and build output, improving compile times.
[workspace]
members = [
"app",
"utils",
"core"
]
Running Specific Binaries
A project may contain multiple binary targets.
cargo run --bin app
This allows precise control over which executable is run.
Cargo.lock File
The Cargo.lock file records exact dependency versions.
It ensures consistent builds across machines.
- Commit
Cargo.lockfor applications - Ignore it for libraries
Why Advanced Cargo Matters
Advanced Cargo usage helps you:
- Manage large Rust codebases
- Optimize build performance
- Control binary size
- Work with teams effectively
📝 Practice Exercises
Exercise 1
Build a project using the release profile.
Exercise 2
Enable a feature from a dependency.
Exercise 3
Create a workspace with two crates.
Exercise 4
Run a specific binary target.
✅ Practice Answers
Answer 1
cargo build --release
Answer 2
serde = { version = "1.0", features = ["derive"] }
Answer 3
[workspace]
members = ["crate1", "crate2"]
Answer 4
cargo run --bin my_app
What’s Next?
In the next lesson, you will learn about File Handling in Rust, including reading from and writing to files safely.