Cargo in Depth
# Cargo.toml
[package]
name = "my_project"
version = "0.1.0"
edition = "2021"
authors = ["You <you@example.com>"]
description = "A great project"
license = "MIT"
[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.11", features = ["json"] }
chrono = "0.4"
[dev-dependencies]
# Only for tests and benchmarks
mockall = "0.11"
proptest = "1"
[build-dependencies]
cc = "1" # For build scripts
[features]
default = ["std"]
std = []
async = ["tokio"]
[profile.release]
opt-level = 3
lto = true
codegen-units = 1 # Better optimization, slower compile
[profile.dev]
opt-level = 0 # Fast compilation
debug = trueEssential Cargo Commands
# Project management
cargo new my_app # Binary project
cargo new --lib my_lib # Library project
cargo init # Init in existing directory
# Building
cargo build # Debug build
cargo build --release # Optimized build
cargo check # Fast syntax/type check (no codegen)
# Running and testing
cargo run # Build and run
cargo run -- arg1 arg2 # Pass args to program
cargo test # Run all tests
cargo test my_test # Run matching tests
cargo bench # Run benchmarks
# Dependencies
cargo add serde --features derive # Add dependency
cargo remove serde # Remove dependency
cargo update # Update all deps
cargo outdated # See outdated deps
# Documentation
cargo doc --open # Build and open docs
cargo doc --no-deps # Just your crate's docs
# Publishing and packaging
cargo login # Authenticate with crates.io
cargo publish # Publish to crates.io
cargo package # Create .crate file
# Useful extras
cargo fmt # Format code with rustfmt
cargo clippy # Lint with Clippy
cargo audit # Check for security vulnerabilities🎯 Practice
- Create a new project and add serde, serde_json as dependencies using cargo add
- Add a dev-dependency and write a test that uses it
- Create a feature flag that enables optional functionality
- Run cargo clippy and fix any warnings it finds
🎉 Key Takeaways
- Cargo.toml controls everything: dependencies, features, profiles, metadata
- cargo add/remove modifies Cargo.toml automatically
- cargo check is much faster than cargo build - use constantly during dev
- cargo clippy gives excellent idiomatic advice beyond the compiler