Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 132 ยท Getting Started

How Rust Works: rustc, Cargo and the Toolchain

See what happens between your Rust source and a running program: rustc, MIR, LLVM, Cargo, rustup, crates.io, debug versus release builds, editions and what the compiler checks.

When you press Run on a Rust example, a lot happens in about a second: your text is parsed, checked, transformed, optimized and turned into a native program, which is then started. Knowing the outline of this pipeline makes many Rust rules less mysterious. It explains why the compiler is so strict, why compiling is slower than in Go, why the resulting programs are fast, and why "debug" and "release" builds behave differently.

This lesson tours the toolchain: rustup, rustc and cargo, the stages of compilation, the difference between the standard library and crates, and what the compiler actually verifies. It uses small runnable programs to show the effects. The next lesson then starts on the shape of Rust code itself.

The tools you install

You install Rust with a small program called rustup, the toolchain manager. It downloads and updates three things you use every day:

  • rustc, the compiler. It turns Rust source code into an executable or a library.
  • cargo, the build tool and package manager. Almost nobody runs rustc directly; you run cargo build, cargo run and cargo test, and Cargo calls rustc with the right arguments, downloads dependencies and caches results. The Cargo lesson covers it.
  • The standard library, plus tools such as rustfmt (formatter) and clippy (linter) that you can add.

rustup also lets you keep several channels side by side: stable (released every six weeks, the one you should use), beta (the next stable) and nightly (the experimental one, with unfinished features). It can install a specific version too, for example rustup install 1.99.0. A project can pin its version with a rust-toolchain.toml file so that everyone on a team builds with the same compiler.

Terminal
# read-only: commands you would run on your own computer
rustup update            # get the newest stable toolchain
rustc --version          # print the compiler version
cargo --version          # print the Cargo version
rustup target add wasm32-unknown-unknown   # add a cross-compilation target

Our online editor runs the real rustc on a server, so you do not need to install anything to follow this tutorial. You will want rustup on your own machine as soon as you build a project with more than one file.

From source to machine code

Rust is an ahead-of-time compiled language. Unlike Python or JavaScript, there is no interpreter or virtual machine that reads your source while the program runs. The compiler translates the whole program into machine code for one processor architecture in advance, and what you ship is that machine code. That is the first reason Rust programs start instantly and run fast.

Inside rustc the translation goes through several stages. You rarely look at them, but their names appear in documentation and error messages:

  1. Parsing. Your text becomes an abstract syntax tree (AST). Macros such as println! are expanded here, which is why a mistake in a format string is reported as a compile error rather than at run time.
  2. Name resolution and type checking. The compiler figures out what every name refers to and infers the type of every expression. Errors like E0425 (unknown name) and E0308 (mismatched types) come from this stage.
  3. MIR (Mid-level Intermediate Representation). The program is lowered to a simple control-flow form. The borrow checker works on MIR. This is where the ownership rules you will learn in the next chapters are enforced, and where errors such as E0382 (use of moved value) are produced.
  4. Monomorphization. Generic code is copied once per concrete type you use. A generic function used with i32 and f64 becomes two separate machine-code functions, each as fast as if you had written it by hand. This is the "zero-cost" in zero-cost abstractions, and its price is somewhat larger binaries and longer compile times. See generics.
  5. LLVM. The result is handed to LLVM, a mature compiler backend also used by Clang and Swift. LLVM optimizes (inlining, loop unrolling, vectorization) and emits machine code for your target.
  6. Linking. The pieces are joined with the parts of the standard library you use and with any libraries, producing one executable.

Because most of the safety checking happens in the early stages and most of the optimizing in the later ones, you can run cargo check to get the errors in a fraction of the time of a full build. It stops before code generation. Many Rust developers run it constantly while editing.

Mostly one file

The result is typically a single self-contained executable. The Rust standard library is linked statically, so the binary does not need a runtime installed on the target machine (on Linux it still uses the system C library by default, but there are fully static targets too). To run your program elsewhere you copy one file. This is why Rust is so popular for command-line tools.

Debug and release builds

Cargo builds in two main profiles:

  • cargo build makes a debug build. Compilation is fast, optimizations are off, and extra run-time checks are on.
  • cargo build --release makes a release build. Compilation is much slower, optimizations are on, and the program can easily be ten to a hundred times faster.

The most visible difference is integer overflow. In a debug build, adding past the maximum of a type panics. In a release build, by default, the number silently wraps around. Our editor compiles with overflow checks on, so you can see the debug behavior:

Rust Overflow panics in a debug build (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program parses 250 at run time (so the compiler cannot see the value ahead of time), then big + 10 is 260, which does not fit in a u8 (maximum 255). The run ends with a panic: attempt to add with overflow. The panic message names the file and line, and the exit code is 101.

You can ask which kind of build you are in with cfg!(debug_assertions), a compile-time check that is true in debug builds:

Rust Which build is this?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

debug_assert! is a check that exists only when debug assertions are on; in release builds it disappears completely, so you can use it for expensive sanity checks. The last two lines show the explicit alternatives to relying on build mode: checked_add returns None on overflow and wrapping_add wraps on purpose. When overflow matters, say what you mean with these methods instead of depending on the profile. The overflow lesson goes deeper.

Always measure performance with --release. A debug build can be dramatically slower, because it keeps overflow checks, skips inlining and keeps every variable in memory. Comparing a debug Rust program to a release build of another language is one of the most common benchmarking mistakes.

Crates, the standard library and crates.io

The unit of compilation in Rust is the crate. A crate is either a binary crate (it has a main function and builds an executable) or a library crate (it builds code for others to use). A bigger project may contain several crates; a group of them managed together is a package or workspace.

The standard library, called std, comes with the compiler. It contains the fundamental types (Option, Result, String, Vec), collections, I/O, threads, and more. Underneath it are two smaller layers: core (no operating system needed, the part that works on tiny devices) and alloc (heap-allocating types). Everything in core is re-exported by std, so for normal programs you only write std::....

Everything beyond std comes from crates, mostly published on crates.io, the community's package registry. Rust deliberately keeps its standard library small and stable; things like random numbers (rand), JSON (serde_json), regular expressions (regex) and the async runtime (tokio) live in crates. You add a dependency by a line in Cargo.toml, and Cargo downloads, compiles and caches it for you.

TOML
# read-only: Cargo.toml of a project that uses external crates
[package]
name = "demo"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.9"
serde_json = "1"

Our editor runs a single file with the standard library only, so the lessons that discuss crates show their code in read-only blocks, and they supply small hand-written stand-ins that run here. You will see this in Crates and Dependencies and Random numbers and hashing.

This program uses only std, imported with use:

Rust Using the standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A BTreeMap keeps its keys sorted, which is why the output is in alphabetical order. (A HashMap would give a different, randomized order on each run, so lessons use BTreeMap when they print whole maps.) {name:<8} pads the name to eight characters, left-aligned; printing explains this notation.

Editions are decided per crate

Each crate chooses an edition in its Cargo.toml (edition = "2024"), and rustc is told with --edition 2024. Editions can change syntax, reserve new keywords or adjust small rules, but never the meaning of compiled code, so a 2015-edition library can be a dependency of a 2024-edition program. A tool called cargo fix --edition can migrate most code automatically.

The 2024 edition reserved the word gen for future use. Using it as a name is therefore an error that older editions would have allowed:

Rust gen is reserved in edition 2024 (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler says expected identifier, found reserved keyword gen``, and suggests the raw identifier form r#gen, which lets you use any keyword as a name when you have to (for example when you talk to old code). Renaming the variable is the simpler fix; the second error in the output is only a consequence of the first.

What the compiler actually checks

It helps to know the categories of errors so that you know what kind of problem you are looking at:

  • Syntax errors: a missing brace or an unexpected token.
  • Name errors: using something that is not defined or not imported (E0425, E0433).
  • Type errors: a value of the wrong type (E0308). Rust never converts types silently, which prevents a whole class of surprises.
  • Ownership and borrowing errors: using a value after moving it, or holding conflicting references (E0382, E0499, E0502). These are the famous ones, and they are what gives Rust its memory safety.
  • Lifetime errors: a reference that might outlive the data it points to (E0106, E0597).
  • Trait errors: calling something on a type that does not support it, or an incomplete implementation (E0277, E0046).
  • Exhaustiveness errors: a match that does not cover every case (E0004), so adding a variant to an enum shows you everything that needs updating.
  • Lints and warnings: unused variables, unreachable code and similar. These do not stop the build, but treat them seriously; clippy adds many more.

Here is a type error, the kind you will meet on day one:

Rust Types never convert silently (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message error[E0308]: mismatched types says it expected i64 and found i32, and the help suggests count.into(). Rust refuses to widen the number behind your back, because implicit conversions are a classic source of bugs. The fix is an explicit conversion, taught in type conversion.

The big idea behind all of these checks is that they happen before the program runs. A Rust program that compiles has already passed a demanding examination, so most of your debugging time goes into conversations with the compiler instead of hunting crashes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between cargo check and cargo build?

    cargo check performs parsing, type checking and borrow checking but skips code generation and linking. It is the quick way to see compiler errors.
  2. 2. A program adds 1 to a u8 holding 255. What happens in a debug build and in a default release build?

    Overflow checks are on in debug builds (panic) and off by default in release builds (two's complement wrapping). Use checked_add, wrapping_add or saturating_add to state the behavior you want.
  3. 3. What does monomorphization mean?

    Each concrete instantiation of a generic function or type gets its own optimized machine code. This makes generics as fast as hand-written code, at the cost of larger binaries.
  4. 4. Where does the borrow checker run, and which error code is typical for it?

    The borrow checker analyses the MIR form of your program, before LLVM. Errors such as E0382, E0499 and E0502 come from it.
  5. 5. Why can a crate written for the 2015 edition be a dependency of a 2024 program?

    Each crate is compiled with its own edition, and editions do not change the compiled interface. That is how Rust evolves without splitting the ecosystem.

Summary

  • rustup manages toolchains (stable, beta, nightly), rustc compiles, and cargo builds, runs, tests and manages dependencies.
  • Rust compiles ahead of time to native machine code: source, then AST, then MIR (borrow checking), then LLVM, then a linked executable.
  • Generics are monomorphized: one specialized copy per concrete type, which is fast but increases binary size and compile time.
  • Debug builds are quick to compile and check overflow; release builds (--release) are optimized and wrap on overflow by default. Measure speed only in release mode.
  • std sits on core and alloc; everything else comes from crates, mostly via crates.io.
  • Editions (2015, 2018, 2021, 2024) are chosen per crate and can interoperate.
  • The compiler catches syntax, name, type, ownership, lifetime, trait and exhaustiveness errors before the program ever runs.

Next: Rust Syntax