Day 7 · Concept 18
Cargo & crates
One tool runs the entire workflow: build, test, doc, publish, format, lint. crates.io is the central registry. Cargo.toml declares dependencies; Cargo.lock pins exact versions.
1 · The commands you'll use daily
| Command | What it does |
|---|---|
cargo new myapp | Scaffold a new binary project (use --lib for library). |
cargo run | Build (if needed) and run the binary. |
cargo build [--release] | Build. --release optimises; default is fast-compile debug. |
cargo test | Run all tests, including doc tests. |
cargo check | Type-check only. Faster than full build. |
cargo doc --open | Build HTML docs and open them. |
cargo fmt | Format the whole tree to canonical style. |
cargo clippy | The lint pass. Often catches subtle issues. |
cargo add serde | Add a dependency to Cargo.toml. |
cargo update | Refresh Cargo.lock within the version ranges in Cargo.toml. |
2 · Cargo.toml — the manifest
[package]
name = "myapp"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }
reqwest = "0.12"
anyhow = "1"
thiserror = "1"
[dev-dependencies]
proptest = "1"Semver caret. "1" means "anything 1.x.y but not 2.0".
For exact pins, use "=1.2.3". Cargo.lock stores the resolved
versions and should be checked in for binaries, ignored for libraries.
3 · Workspaces — many crates, one repo
[workspace]
members = ["api", "core", "cli"]
resolver = "2"
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
tokio = { version = "1", features = ["full"] }Shared target/, shared lockfile. Inside each sub-crate, depend on workspace deps with serde = { workspace = true }.
4 · Crates worth knowing
| Crate | For |
|---|---|
serde + serde_json | JSON, YAML, etc. The serialization standard. |
tokio | Async runtime. The default choice. |
reqwest | HTTP client. |
axum / actix-web | HTTP servers. |
clap | CLI argument parsing. |
anyhow + thiserror | Errors. Pair them. |
tracing | Structured logging and spans. |
sqlx / diesel | Database access. |
rayon | Easy data parallelism — replace .iter() with .par_iter(). |
5 · Common mistakes
- Forgetting feature flags. Many crates ship with minimal features by default —
tokioneedsfeatures = ["full"]for the macros. - Running
cargo buildwhen you meant--release. Debug builds are easily 10× slower at runtime. - Committing
target/. It's huge. Make sure it's in.gitignore(cargo new does this). - Ignoring clippy. It catches real bugs, not just style.
6 · When it clicks
cargo checkis your inner loop, notcargo run.- You add a crate with
cargo add foowithout thinking about it. cargo clippyruns in CI on every PR.
Found this useful?