Cargo and your first program

Rust · Essentials · 10 min

Cargo is how every Rust project is built, run, tested and shared, so it is the first tool you touch.

Rust is installed with rustup, which manages toolchains (stable, beta, nightly) and keeps them updated with rustup update. It also installs rustc, the compiler, and Cargo, the build tool and package manager. In practice you almost never call rustc directly.

cargo new hello creates a package: a Cargo.toml manifest and src/main.rs. The manifest names the package, sets edition = "2024" (the language edition, which controls a few syntax and lint defaults) and lists dependencies.

The everyday commands:

  • cargo run compiles in debug mode and runs the binary.
  • cargo build --release builds an optimized binary into target/release/. Debug builds are fast to compile but can be 10-50x slower at runtime, so always benchmark release builds.
  • cargo check type-checks without producing a binary. It is much faster, so use it constantly while editing.
  • cargo fmt formats code and cargo clippy runs the linter; both are standard in real projects.

Every binary starts at fn main(). println! is a macro (note the !), which is how Rust supports format strings that are checked at compile time. Placeholders are {} for user-facing Display output and {:?} for Debug output, and you can put variable names inline: println!("{name}").

The compiler's error messages are unusually good. Read them fully: they usually point at the exact span and often suggest the fix.

Example

// $ cargo new hello && cd hello
// Cargo.toml contains: edition = "2024"
// src/main.rs:
fn main() {
    let name = "Rust";
    let year = 2024;
    println!("Hello, {name}!");             // Hello, Rust!
    println!("Edition {}", year);           // Edition 2024
    println!("Debug view: {:?}", (1, "a")); // Debug view: (1, "a")
}
// $ cargo run          -> compile (debug) and run
// $ cargo check        -> fast type-check only
// $ cargo build --release

Remember

  • cargo new, cargo run, cargo check, cargo build --release cover daily work
  • {} uses Display, {:?} uses Debug; names can go inline as {name}
  • Measure performance only on release builds

Watch out for

  • Benchmarking a debug build and concluding Rust is slow.

Check yourself

  1. You are iterating on code and only want to know whether it compiles. Which command is fastest?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: doc.rust-lang.org/book/ch01-03-hello-cargo.html

Builds on

Nothing: this is a foundation.

Unlocks