Cargo is the one ring to rule them all. It creates the project, downloads the dependencies, builds the code, and gives the finished binary somewhere sensible to live. Cargo, packaging, you get it. Terrible joke, useful tool.
What does Cargo do for a Rust project?
Think beyond compilation. Cargo owns the ordinary project loop.
Reveal the answer
Cargo creates projects, manages dependencies, checks and builds the code, runs it, and produces optimized release binaries.
Create a project
Cargo is installed with Rust. I can confirm it is available with:
cargo --versionThen I can create a binary project named hworld:
cargo new hworld
cd hworldCargo gives me the small project skeleton I need:
hworld
├── Cargo.toml
└── src
└── main.rs
src/main.rs contains the code. Cargo.toml is the manifest, where the project name, version, Rust edition, and dependencies live.
[package]
name = "hworld"
version = "0.1.0"
edition = "2021"
[dependencies]Build and run it
cargo buildThe debug binary lands in target/debug/hworld. I can run that file directly, but the command I use most often is:
cargo runThat builds the project when needed and immediately runs it:
Compiling hworld v0.1.0
Finished `dev` profile [unoptimized + debuginfo]
Running `target/debug/hworld`
Hello, world!
Check without producing the binary
When I mainly want the compiler to tell me whether the project is valid, cargo check is usually faster than a full build:
cargo checkIt type-checks and validates the project without doing all the work required to write the final executable.
Build an optimized release
cargo build --releaseThe optimized binary lands in target/release/hworld. I like that Cargo names everything roughly where I expect it to be. There are fewer little gotchas to remember.
What I keep in my head
Use cargo check while editing, cargo run to build and execute, and cargo build --release when I want the optimized binary.