Rust Cargo Cheat Sheet
Reference for Cargo commands, Cargo.toml structure, dependency management, workspaces, and common cargo subcommands for building and testing Rust projects.
Basic Commands
The core cargo workflow for building and running projects.
cargo new my_project # Create a new binary projectcargo new --lib my_lib # Create a new library projectcargo build # Compile in debug mode (target/debug)cargo build --release # Compile with optimizations (target/release)cargo run # Build and run the binarycargo run -- arg1 arg2 # Pass arguments to the binarycargo check # Fast type-check without producing a binarycargo test # Run all testscargo test test_name # Run tests matching a name filter
Cargo.toml
The project manifest that declares metadata and dependencies.
[package]name = "my_project"version = "0.1.0"edition = "2021"[dependencies]serde = { version = "1.0", features = ["derive"] }tokio = { version = "1", features = ["full"] }rand = "0.8"[dev-dependencies]criterion = "0.5"[profile.release]opt-level = 3lto = true
Common Subcommands
Frequently used cargo tooling commands.
- cargo fmt- Formats source code according to rustfmt rules
- cargo clippy- Runs the Clippy linter for idiomatic-code suggestions and common mistakes
- cargo doc --open- Builds and opens crate documentation in a browser
- cargo add <crate>- Adds a dependency to Cargo.toml (Cargo 1.62+)
- cargo update- Updates dependencies in Cargo.lock to the latest compatible versions
- cargo publish- Publishes the crate to crates.io
- cargo tree- Prints the dependency tree, useful for debugging version conflicts
- cargo clean- Removes the target directory build artifacts
Workspaces
Managing multiple related crates in a single repository.
# Top-level Cargo.toml for a multi-crate workspace[workspace]members = [ "app", "core", "cli",]resolver = "2"[workspace.dependencies]serde = { version = "1.0", features = ["derive"] }# cargo build --workspace # Build every crate in the workspace# cargo test -p core # Run tests only for the "core" package
Dependency Version Specs
Syntax for constraining dependency versions in Cargo.toml.
- "1.2.3"- Caret requirement (default); allows updates that don't change the leftmost non-zero digit
- "=1.2.3"- Exact version requirement, no automatic updates
- "~1.2"- Tilde requirement; allows patch-level updates only (1.2.x)
- git = "url"- Pulls a dependency directly from a Git repository
- path = "../local-crate"- Uses a local path dependency, common in workspaces
- features = [...]- Enables optional, opt-in functionality exposed by the dependency
- default-features = false- Disables a dependency's default feature set to reduce compile time/size
build.rs Build Scripts
A build.rs file runs before compilation to generate code, link native libraries, or set cfg flags.
// build.rs (placed at the crate root, next to Cargo.toml)fn main() { // Re-run this script only if build.rs itself or the given file changes println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=src/schema.proto"); // Link a native library found on the system println!("cargo:rustc-link-lib=z"); // Emit a custom cfg flag consumable via #[cfg(has_feature_x)] println!("cargo:rustc-cfg=has_feature_x"); // Pass a value to the crate as an env var at compile time println!("cargo:rustc-env=BUILD_TIMESTAMP={}", chrono_like_stamp());}fn chrono_like_stamp() -> String { "2026-07-21".to_string()}
Feature Flags & Conditional Compilation
Cargo features toggle optional code paths and dependencies, gated with #[cfg(feature = "...")].
[features]default = ["std"]std = []async = ["dep:tokio"]full = ["std", "async", "serde"]serde = ["dep:serde"][dependencies]tokio = { version = "1", optional = true }serde = { version = "1", optional = true }# In code:# #[cfg(feature = "async")]# async fn fetch() { /* ... */ }## cargo build --features async# cargo build --no-default-features --features std
Advanced Cargo Tooling
Ecosystem subcommands beyond the built-in ones, installed via cargo install.
- cargo audit- Scans Cargo.lock against the RustSec advisory database for known-vulnerable dependencies
- cargo deny check- Enforces license, ban, and duplicate-version policies defined in deny.toml
- cargo expand- Prints the fully macro-expanded source, invaluable for debugging derive/proc macros
- cargo udeps- Detects unused dependencies declared in Cargo.toml (requires nightly)
- cargo nextest run- Faster, more parallel test runner with better output than the built-in cargo test
- cargo bench- Runs benchmarks, typically backed by the criterion crate on stable Rust
- cargo-cross- Cross-compiles for a target triple using a preconfigured Docker toolchain image
.cargo/config.toml
Project- or user-level configuration for build targets, aliases, and registry mirrors.
# .cargo/config.toml (project root or ~/.cargo/config.toml)[build]target = "x86_64-unknown-linux-musl"rustflags = ["-C", "target-cpu=native"][alias]b = "build"t = "test"ci = "check --all-targets --all-features"[target.x86_64-unknown-linux-gnu]linker = "clang"[net]git-fetch-with-cli = true
Target-Specific & Workspace-Inherited Dependencies
Dependencies can be gated per platform, and workspace members can inherit shared versions.
# Only pulled in when compiling for Windows[target.'cfg(windows)'.dependencies]winapi = { version = "0.3", features = ["winuser"] }# Only pulled in when compiling for Unix-like targets[target.'cfg(unix)'.dependencies]libc = "0.2"# In a member crate's Cargo.toml, inherit versions from [workspace.dependencies][dependencies]serde = { workspace = true }version = { workspace = true }
Commit Cargo.lock for binary applications (reproducible builds) but omit it for libraries, so downstream consumers resolve dependency versions against their own lockfile.