Cargo Essentials: Workspaces, Features, Clippy and More
Cargo is Rust's build tool and package manager. It's one of the best parts of the language, and a few features make a big difference in real projects.
Everyday commands
cargo new myapp # binary project (--lib for a library)
cargo add serde --features derive
cargo build --release # optimised build in target/release
cargo run -- --port 8080 # args after -- go to your program
cargo test
cargo check # type-check without building: very fast
cargo fmt # format code
cargo clippy # lints and suggestions
cargo doc --open # docs for your crate and its dependencies
Clippy is a free code review
// clippy: this could be written as `!names.is_empty()`
if names.len() > 0 { /* ... */ }
Run cargo clippy -- -D warnings in CI to fail builds on lint warnings.
Feature flags
[features]
default = ["json"]
json = ["dep:serde_json"]
postgres = ["dep:sqlx"]
[dependencies]
serde_json = { version = "1", optional = true }
sqlx = { version = "0.8", optional = true, features = ["postgres", "runtime-tokio"] }
#[cfg(feature = "postgres")]
pub mod pg_store;
Features let users compile only what they need, which keeps build times and binaries small.
Workspaces
# Cargo.toml at the repo root
[workspace]
resolver = "3"
members = ["api", "worker", "shared"]
[workspace.dependencies]
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
# api/Cargo.toml
[dependencies]
tokio = { workspace = true }
shared = { path = "../shared" }
All crates share one Cargo.lock and one target directory, so builds are shared and versions stay consistent.
Speeding up builds
- Use
cargo checkwhile coding; build only when you need to run. - Split large crates so changes recompile less.
- In CI, cache
~/.cargoandtarget/.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.