Mastering Cargo

Mastering Cargo in Rust: Imagine commissioning a piece of furniture. You could buy the timber yourself, drive to three suppliers for the right hinges, work out…

The Analogy: The Contractor Who Keeps the Bill of Materials

Imagine commissioning a piece of furniture. You could buy the timber yourself, drive to three suppliers for the right hinges, work out the assembly order, and keep a notebook of which screws came from where. That is a perfectly workable way to build a cabinet, and it is also how building software in C and C++ has traditionally felt: a hand-written Makefile, a hunt for the correct header path, and a folder of dependencies whose versions live in your memory rather than in a file.

Now imagine a contractor instead. You hand over a one-page specification. The contractor keeps a bill of materials listing every part and the acceptable range of part numbers, orders exactly those parts, records the specific serial numbers that actually arrived so the next build is identical, and knows the assembly order without being told. If you ask for a second, sturdier version of the same cabinet, the contractor already knows which glue to use for the heavy-duty variant.

Cargo is that contractor, and the detail that matters is that it came in the same box as the language. Python has pip, venv, poetry, uv, and a decade of argument about which to use. JavaScript has npm, yarn, and pnpm, and its lockfile arrived years after the ecosystem did. C++ has CMake plus a choice of package managers, none of which is standard. Rust shipped one build tool, one project layout, and one lockfile format on day one, and the entire ecosystem agreed by default.

The practical consequence is that every Rust project you will ever clone looks the same. src/main.rs is a program, src/lib.rs is a library, cargo test runs the tests, cargo build --release produces the fast binary. You do not read a project's build system to find out how to build it, which sounds like a small convenience until you have spent an afternoon reverse-engineering somebody else's makefile.


Syntax or Core Structure

One command creates a project:

cargo new weather
cd weather

That gives you a directory with exactly four things in it:

weather/
|-- .git/
|-- .gitignore
|-- Cargo.toml
`-- src/
    `-- main.rs

Cargo.toml is the bill of materials, and a new one is deliberately tiny:

[package]
name = "weather"
version = "0.1.0"
edition = "2024"

[dependencies]

Building and running it takes one more command:

cargo run

Output:

   Compiling weather v0.1.0 (/home/you/weather)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.38s
     Running `target/debug/weather`
Hello, world!

Two parts of that transcript are yours rather than universal: the path in parentheses is wherever you happen to be working, and the elapsed figure on the Finished line is whatever your machine took. Everything else is stable, including the important detail that the profile is named dev and the binary landed in target/debug/. Run cargo run a second time without editing anything and the Compiling line disappears, because Cargo compares file timestamps and hashes and does nothing it does not have to.


Technical Depth: The Parts of Cargo Worth Knowing Early

The commands, and which one belongs in your edit loop

CommandWhat it doesWhen you reach for it
cargo checktypechecks and borrow-checks, then stopsthe tightest loop; it skips code generation and is commonly three to ten times faster than a build
cargo buildcompiles into target/debug/you actually need the binary
cargo runbuilds, then executesday-to-day iteration on a program
cargo testbuilds a test harness and runs unit, integration, and documentation testsbefore every commit
cargo build --releaseoptimises into target/release/shipping, and any measurement you intend to quote
cargo add serdeedits Cargo.toml for you, picking a sensible version requirementadding a dependency, since Cargo 1.62
cargo treeprints the resolved dependency graphanswering "why is this crate in my build at all"
cargo doc --openrenders documentation for your crate and every dependencyreading an unfamiliar API offline
cargo clippyruns the extended lint setbefore review
cargo fmtrewrites your source in canonical stylebefore review
cargo cleandeletes target/reclaiming disk, or ruling out a stale-artifact theory

The habit worth forming on day one is using cargo check while you are writing and cargo build only when you want to run something. Because the borrow checker runs during check, you get the entire safety analysis without paying for optimisation and linking, which is where most of the compile time actually goes.

The layout is a convention, not configuration

PathMeaning
src/main.rscrate root of a binary named after the package
src/lib.rscrate root of a library
src/bin/tool.rsan extra binary, run with cargo run --bin tool
tests/integration tests; each file is compiled as its own separate crate
benches/benchmarks
examples/complete runnable programs, via cargo run --example name
build.rsa build script compiled and run before your crate
target/every artifact Cargo produces; never committed

A single package may contain both src/lib.rs and src/main.rs, and that pairing is the standard shape for a command-line tool: the library holds the logic and is testable and reusable, the binary is a thin shell that parses arguments and calls into it. The distinction between tests/ and #[cfg(test)] modules matters more than it looks, because a file in tests/ can only reach your crate's public API, exactly as an outside user would.

Cargo.toml states intent; Cargo.lock records fact

Cargo.toml is written by you and holds ranges: which versions you are willing to accept. Cargo.lock is written by Cargo and holds exact versions plus checksums: what the resolver actually chose. The split is what makes builds both flexible and reproducible, and misreading it is the source of most dependency confusion.

A bare version string is not an exact version. It is a caret requirement:

Written in Cargo.tomlActually means
serde = "1.0.188">=1.0.188, <2.0.0
serde = "^1.2">=1.2.0, <2.0.0 (identical to "1.2")
serde = "~1.2.3">=1.2.3, <1.3.0
serde = "=1.2.3"exactly 1.2.3, nothing else
tiny = "0.3.1">=0.3.1, <0.4.0
tiny = "0.0.3">=0.0.3, <0.0.4
anything = "*"any version at all; crates.io refuses to publish this

The last three rows encode a rule worth memorising: before 1.0, the leftmost non-zero number is treated as the breaking one. A crate at 0.3 may break your code when it releases 0.4, and the caret rule protects you from that automatically. This is why so much of the ecosystem sits at 0.x deliberately, and why upgrading a 0.x dependency is a real code review rather than a version bump.

cargo update moves your lockfile forward to the newest versions still allowed by those ranges, and cargo update -p serde limits that to a single crate. Nothing else changes your locked versions: adding an unrelated dependency will not silently upgrade the ones you already have.

Commit Cargo.lock for anything you deploy, so that the binary built by CI is byte-for-byte the one you tested. For a library the question used to be contentious, because a consumer's build ignores your lockfile entirely and resolves from their own. The modern answer is to commit it anyway: it makes your own CI reproducible and costs downstream users nothing.

One more field earns its place in every serious Cargo.toml:

[package]
name = "weather"
version = "0.1.0"
edition = "2024"
rust-version = "1.82"

rust-version declares your minimum supported Rust version. Cargo refuses to build with an older toolchain and says so clearly, which is far kinder than the wall of syntax errors you would otherwise get, and it lets the resolver avoid dependency versions that need a newer compiler than you support.

Profiles: the same source, two very different binaries

dev and release are not a small difference in optimisation flags. They are different contracts.

SettingdevreleaseWhat it controls
opt-level03how hard the optimiser works
debugtruefalsewhether debug info is emitted
debug-assertionstruefalsewhether debug_assert! runs
overflow-checkstruefalsewhether integer overflow panics
incrementaltruefalsereuse of previous compilation work
codegen-units25616build parallelism, traded against optimisation quality
ltofalsefalselink-time optimisation across crates
panicunwindunwindwhether a panic unwinds or aborts

The overflow-checks row is the one that bites. It is why the intro lesson could promise that i32::MAX + 1 panics in development and wraps in release: same code, two profiles, two behaviours. The opt-level row is why a debug build can be an order of magnitude slower and why no performance number is meaningful without its profile attached.

You can push release further:

[profile.release]
lto = "fat"
codegen-units = 1
panic = "abort"
strip = true

This trades build time for a smaller, faster binary: whole-graph inlining, no unwinding tables, no symbols. Two caveats belong with it. panic = "abort" means std::panic::catch_unwind can no longer recover anything, so any code relying on it must go; Cargo ignores the setting for the test and bench profiles, so cargo test keeps working. And every one of these should be measured rather than assumed, because codegen-units = 1 in particular can cost minutes of build time for a percent or two of speed.

Features are additive, and that has consequences

[dependencies]
serde = { version = "1.0", default-features = false, features = ["derive"] }

Features are compile-time flags a crate exposes. default-features = false opts out of the ones it enables for you, which is the standard move for embedded targets that cannot use the standard library. The rule that catches people is unification: if your dependency graph contains two crates that want different feature sets of serde, Cargo compiles serde once with the union of them. A feature you never asked for can therefore appear in your build because something three levels down wanted it, and features must be purely additive for this to be sound. A "feature" that removes an item or changes a signature will break somebody, which is why you will see no_std expressed as default-features = false rather than as a no-std feature.


Real World Example: A Two-Crate Workspace

Real projects outgrow a single src/main.rs quickly, and the shape they grow into is a workspace: several packages that share one target/ directory, one Cargo.lock, and one set of resolved dependency versions. Here is the smallest workspace that is still worth writing, a library of conversions and a program that prints a table with them.

weather/
|-- Cargo.toml
|-- Cargo.lock
`-- crates/
    |-- tempconv/
    |   |-- Cargo.toml
    |   `-- src/
    |       `-- lib.rs
    `-- report/
        |-- Cargo.toml
        `-- src/
            `-- main.rs

The root manifest has no [package] section at all, which makes it a virtual manifest: it exists to describe the set, not to be built itself.

# weather/Cargo.toml
[workspace]
members = ["crates/*"]
resolver = "2"

[workspace.package]
edition = "2024"
rust-version = "1.85"

[workspace.dependencies]
tempconv = { path = "crates/tempconv" }
# weather/crates/tempconv/Cargo.toml
[package]
name = "tempconv"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
# weather/crates/report/Cargo.toml
[package]
name = "report"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true

[dependencies]
tempconv.workspace = true

The library is four lines of logic and two tests:

// weather/crates/tempconv/src/lib.rs
//! Temperature conversions used by the weather report.

/// Converts a Celsius reading to Fahrenheit.
pub fn c_to_f(c: f64) -> f64 {
    c * 9.0 / 5.0 + 32.0
}

/// Converts a Fahrenheit reading to Celsius.
pub fn f_to_c(f: f64) -> f64 {
    (f - 32.0) * 5.0 / 9.0
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn freezing_point() {
        assert_eq!(c_to_f(0.0), 32.0);
    }

    #[test]
    fn round_trip_is_stable() {
        let c = 21.5;
        assert!((f_to_c(c_to_f(c)) - c).abs() < 1e-9);
    }
}

And the binary is the thin shell that only formats:

// weather/crates/report/src/main.rs
use tempconv::{c_to_f, f_to_c};

fn main() {
    let samples_c = [0.0, 21.5, 37.0, 100.0];

    println!("{:>8}  {:>8}", "C", "F");
    for c in samples_c {
        println!("{c:>8.1}  {:>8.1}", c_to_f(c));
    }

    println!();
    println!("98.6 F is {:.1} C", f_to_c(98.6));
}
cargo run -p report

Output:

   Compiling tempconv v0.1.0 (/home/you/weather/crates/tempconv)
   Compiling report v0.1.0 (/home/you/weather/crates/report)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.44s
     Running `target/debug/report`
       C         F
     0.0      32.0
    21.5      70.7
    37.0      98.6
   100.0     212.0

98.6 F is 37.0 C
cargo test --workspace

Output:

    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.51s
     Running unittests src/lib.rs (target/debug/deps/tempconv-<hash>)

running 2 tests
test tests::freezing_point ... ok
test tests::round_trip_is_stable ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

     Running unittests src/main.rs (target/debug/deps/report-<hash>)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests tempconv

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Three things in those transcripts are not reproducible and are marked as such: the paths, the elapsed times, and the <hash> suffix Cargo appends to each test binary. One more is genuinely non-deterministic even on the same machine: the two test ... ok lines can appear in either order, because the test harness runs tests on a thread pool by default. If you need them serialised, cargo test -- --test-threads=1 will do it.

The .workspace = true lines are worth more than they look. Every crate in this workspace inherits its edition and its minimum Rust version from one place, so the set can never drift into a state where one crate is on the 2021 edition and another on 2024. [workspace.dependencies] does the same job for versions: declare serde = "1.0" once at the root and every member writes serde.workspace = true, which means a version bump is a single-line change instead of a search across a dozen manifests. On a workspace with twenty crates this is the difference between an upgrade taking a minute and taking an afternoon.

The split between the two crates is the standard shape for a tool, and the test output shows why. All the logic that can be wrong lives in tempconv, where it is exercised by two tests that never start a process, never format a table, and never touch standard output. report contains only presentation, which is why its test binary reports running 0 tests: src/main.rs has no #[cfg(test)] module. If you later want the same conversions in a web service, you depend on tempconv and leave report alone.

Notice that cargo test --workspace ran three targets, not two. Test running in Rust is per-target rather than per-package: the library's unit tests, the binary's unit tests, and a separate Doc-tests tempconv pass. That third one exists because tempconv is a library; binaries do not get doc tests. It found nothing here because the doc comments contain no example code, and the Comments and Documentation lesson later in this module is where that section starts reporting real numbers.

Two smaller details in the program tie back to the previous lesson. for c in samples_c iterates an array by value, consuming it, which is a 2021-edition behaviour: on the 2015 and 2018 editions the same line would have iterated references instead. And nothing here declares a build order. Cargo read report's dependency on tempconv, compiled the library first, and shared one target/ directory between them. That is the contractor doing the job you would otherwise be doing by hand: you declared what you wanted, not the order in which to get it.


Common Mistakes

  1. Reading serde = "1.0" as "version 1.0". It is a caret range meaning anything below 2.0.0, so the crate you compile tomorrow may not be the one you compiled today unless a lockfile pins it. If you genuinely need one exact version, write =1.0.188 and accept that you now own the upgrade schedule.
  2. Committing target/. It is generated, it is enormous, and cargo new already wrote a .gitignore containing it. A stray git add -A in a project created some other way is usually how it happens.
  3. Quoting a benchmark from a debug build. Without --release the optimiser is off and overflow checks are on. Any timing from cargo run describes a binary you would never ship.
  4. Editing Cargo.lock by hand. It is a generated file with checksums. Use cargo update, cargo update -p crate, or change the requirement in Cargo.toml and let Cargo rewrite it.
  5. Expecting a file in tests/ to see private items. Integration tests compile as separate crates and can only use your public API. Unit tests that need private access belong in a #[cfg(test)] mod tests block inside the file they test.
  6. Assuming default-features = false on your own dependency disables that feature everywhere. Feature resolution unifies across the whole graph, so if any other crate enables it, it is enabled in the build. cargo tree -f "{p} {f}" will show you who asked.
  7. Adding a dependency by hand and mistyping the name. cargo add serde checks the registry, picks a current version, and cannot typo the crate name into a package that somebody registered hoping you would.
  8. Running cargo build in the edit loop. cargo check gives you every type and borrow error far faster because it never generates machine code. Save build for when you intend to run the result.
  9. Forgetting resolver = "2" in a virtual workspace manifest. With no root package there is no edition to infer it from, so Cargo falls back to the original resolver and warns; on Rust 1.84 and later, resolver = "3" additionally makes version selection respect your rust-version.

Best Practices

  • Let cargo add and cargo update write the manifest and the lockfile. Hand-editing invites typos in exactly the two files where a typo is expensive.
  • Commit Cargo.lock, including for libraries. Deployed artifacts become reproducible, CI stops failing for reasons nobody changed, and downstream users are unaffected because their build resolves from their own lockfile.
  • Set rust-version from the first commit. A clear "requires 1.82" beats a page of syntax errors, and it lets the resolver avoid dependencies that need a newer compiler than you support.
  • Split logic into a library and keep the binary thin. Tests get faster, the logic becomes reusable, and cargo test output tells you immediately which layer broke.
  • Use a workspace as soon as you have two crates, and inherit edition, rust-version, and shared dependency versions from the root. One place to bump, one target/ directory, one lockfile.
  • Keep cargo check in the tight loop and cargo clippy in the commit loop. The first catches your mistakes in seconds; the second teaches idiom.
  • State the profile whenever you state a number. "1.2 ms, release, LTO fat" is data. "1.2 ms" is not.
  • Read cargo tree before blaming a dependency. It answers who pulled a crate in, which version won, and which features were unified, usually in one screen.

Practice Exercises

  1. Build the workspace above from scratch. Create it with cargo new --lib and cargo new, wire up the workspace manifest, and confirm that cargo run -p report reproduces the table exactly, including the column alignment.
  2. Compare the profiles. Add a loop to report that calls c_to_f ten million times and sums the results, then time cargo run -p report against cargo run --release -p report. Record both numbers and the ratio, and state which profile each came from.
  3. Investigate a real dependency graph. In a scratch project, run cargo add serde --features derive, then cargo tree. Write down how many crates were added, which of them you did not ask for, and what serde_derive is there to do.
  4. Break the version requirement on purpose. Change a dependency to "=0.1.0" for a crate whose current version is higher, run cargo build, and read the resolver's error. Then relax it to "0.1" and explain in one sentence why that now resolves.