Flashcard Rust: Cargo

A practical Rust Cargo flashcard covering project creation, dependencies, builds, checks, runs, and optimized release binaries.
coding
rust
Author

unrahul

Published

March 9, 2020

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.

Flashcard 02 Rust

The question

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 --version

Then I can create a binary project named hworld:

cargo new hworld
cd hworld

Cargo 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 build

The debug binary lands in target/debug/hworld. I can run that file directly, but the command I use most often is:

cargo run

That 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 check

It type-checks and validates the project without doing all the work required to write the final executable.

Build an optimized release

cargo build --release

The 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.