Module 9 · Lesson 1 of 24

Why Rust; rustup, cargo, and the basics

Why Rust matters for systems and embedded Linux, then install rustup, drive cargo, and learn the language basics from scratch.

  • Beginner to advanced
  • 28 min read
  • 45 min lab
What you will need

A Linux machine (Ubuntu 24.04 in WSL2, a VM, or a container) with internet access; VS Code with the rust-analyzer extension

By the end you can 7 objectives
  • Explain why Rust matters for systems and embedded programming and name the C/C++ bug classes it prevents.
  • Install and manage Rust toolchains, targets, and components with rustup.
  • Compile a single file with rustc and describe what an edition changes and why old code keeps compiling.
  • Create, build, run, and test a Cargo project and explain its layout and lockfile.
  • Declare dependencies with correct version requirements and update them safely.
  • Write Rust programs using variables, scalar and compound types, functions, and control flow.
  • Read compiler errors and use rustc --explain and rust-analyzer to fix them.
Read the lesson below; the video will appear here when published.
01

Why Rust exists

4 min read

Every systems programmer knows the cost of a language like C or C++. The language gives you direct control over memory: you choose when to allocate, when to free, and exactly where each byte lives. That control is why C and C++ run operating systems, drivers, and firmware. It is also why a whole class of bugs keeps showing up in those codebases, year after year.

is something C and C++ ask the programmer to guarantee by hand. The compiler cannot check it. The four bug classes below are the usual result, and each one is either a crash, silent corruption, or a security hole:

  • Use after free. You free a buffer, then a dangling pointer to it is used again. The memory may have been reused for something else, so you read or write the wrong object.
  • Double free. You free the same allocation twice. The allocator's bookkeeping is corrupted, and the next allocation or free can crash anywhere, far from the real cause.
  • Buffer overflow. You write past the end of an array and clobber whatever sits next to it in memory, often a return address or a pointer.
  • Data race. Two threads touch the same memory without synchronising, and at least one writes. The result depends on timing and is formally undefined behaviour.

Rust's central claim is that it removes these classes without taking away the control that made you choose a systems language in the first place. It does this without a , so there is no pause-for-collection and no runtime you must ship into a small device. Instead, the compiler tracks ownership of every value and enforces the rules at compile time. Code that could use memory after freeing it, or free it twice, or race on it, simply does not compile. Out-of-bounds access is caught by a check the compiler inserts, which makes the program panic the instant it happens instead of silently corrupting its neighbours.

Rust calls the other two pillars of this deal and fearless concurrency. Zero-cost abstractions mean the nice syntax does not cost speed: an iterator that sums an array compiles to the same tight loop as a hand-written index loop. Fearless concurrency means the type system can see, at compile time, which values are safe to share between threads, so data races become a type error rather than a debugging session.

For an embedded Linux engineer this is a direct answer to a painful problem. The code that runs on a board, talks to hardware, and must run for years is exactly the code where a use-after-free or a race is most expensive, because there is no human watching the logs. Rust lets you keep the direct control over memory layout and system calls that embedded work requires, while the compiler takes over the job of proving that your pointers and threads are well behaved.

Memory-safety bug classes: C/C++ vs RustC / C++RustUse after freeRuntime crashor silentcorruptionCompile errorvia theborrowcheckerDouble freeHeapcorruptionCompile errorvia ownershipBuffer overflowSilent memorycorruptionPanic at thebounds checkData raceUndefinedbehaviourCompile errorvia Send/Sync
The four classic C and C++ memory bugs and how Rust stops each one
02

A short history and where Rust is used

4 min read

Rust began as a personal project by Graydon Hoare, who started working on it around 2006. Mozilla began sponsoring it in 2009 and announced it publicly in 2010. The early compiler was written in OCaml; it was later rewritten in Rust itself, a process called self-hosting. The first real testbed was Servo, a browser engine Mozilla was building to explore what a memory-safe systems language could do.

The milestone that matters most is the stability promise. Rust 1.0 shipped in May 2015, and the project committed to never breaking code that compiled on a stable release. This works through a release train, a process where a new stable version is cut every six weeks after passing through the nightly and beta channels:

Step by stepThe six-week release train
  1. Nightly: every night a fresh build is cut from the main branch. New, unstable features live here behind feature flags.

  2. Beta branch: every six weeks a beta branch is split off from nightly and tested against real projects in CI.

  3. Stable release: six weeks after the beta split, a stable release is cut from beta, with the tested features now permanent.

  4. New beta: immediately after the stable cut, the next beta branches off nightly, and the cycle repeats.

Because the schedule is fixed, a feature that misses one release simply rides the next train six weeks later. The three channels, nightly, beta, and stable, are the reason the language can add features constantly while still promising that your stable code never breaks. The same mechanism powers editions, which you will meet shortly.

Mozilla laid off much of its Rust team in 2020, and the independent Rust Foundation was announced in early 2021 to steward the project. Around the same time, Rust made a move that matters enormously for this program: Rust for Linux. Miguel Ojeda's work to add Rust as a second language to the Linux kernel was merged into the mainline kernel in version 6.1, released in late 2022. Since then the kernel has gained in-tree Rust abstractions and real Rust drivers: the first, an Asix Ethernet PHY driver, landed in Linux 6.8 (2024), followed by others such as the Nova driver for NVIDIA GPUs. The best-known Rust driver, Asahi Linux's GPU driver for Apple Silicon, showed the approach works at scale but is still maintained outside the mainline tree. You will build a Rust kernel module yourself in a later module.

Milestones: Rust began around 2006, Mozilla announced it in 2010, Rust 1.0 shipped in May 2015, the Rust Foundation was announced in 2021, Rust for Linux merged into the 6.1 kernel in 2022, and the first in-tree driver landed in 2024.

  • events: [{"date": "2006", "label": "Graydon Hoare starts Rust", "detail": "Rust begins as a personal project, around 2006."}, {"date": "2010", "label": "Mozilla announces Rust", "detail": "Announced publicly after Mozilla began sponsoring it in 2009."}, {"date": "2015-05", "label": "Rust 1.0 released", "detail": "The stability promise: code that compiles on a stable release keeps compiling."}, {"date": "2020", "label": "Mozilla lays off much of its Rust team", "detail": "The project shifts toward independent stewardship."}, {"date": "2021", "label": "Rust Foundation announced", "detail": "An independent foundation is announced to steward Rust."}, {"date": "2022", "label": "Rust for Linux merged", "detail": "Rust merges into the mainline Linux kernel 6.1."}, {"date": "2024", "label": "First in-tree Rust driver", "detail": "An Asix Ethernet PHY driver lands in Linux 6.8."}]

Rust is now used across the industry. Parts of Firefox are written in Rust, as are components of Android and Windows. Cloud infrastructure, command-line tools, and cryptography libraries use it heavily. For embedded work, Rust supports bare-metal targets such as Cortex-M and RISC-V microcontrollers through the embedded-hal ecosystem and async runtimes like Embassy, and it cross-compiles to the same ARM boards you already use for embedded Linux. Tools such as ripgrep, bat, and fd, which you likely already run on your Linux box, are Rust.

The Rust timeline2006GraydonHoarestarts theproject2010MozillaannouncesRust2015Rust 1.0ships2018Rust 2018edition2021Rust 2021edition,RustFoundation2022Rustsupportmerges inLinux 6.12024Rust 2024edition2006GraydonHoarestarts theproject2010MozillaannouncesRust2015Rust 1.0ships2018Rust 2018edition2021Rust 2021edition,RustFoundation2022Rustsupportmerges inLinux 6.12024Rust 2024edition
The key milestones from Rust's first lines in 2006 to the 2024 edition
Why this matters on a board

The promise of memory safety with no garbage collector is unusually attractive for embedded devices. A microcontroller or an industrial ARM board has no room for a runtime that pauses to collect garbage, and a memory bug in a device that runs for years is a field failure you cannot reproduce on your desk. Rust lets a team write firmware and drivers with C-like control and compiler-checked safety.

03

Managing toolchains with rustup

4 min read

A is more than just the rustc compiler. It also includes cargo, the standard library, and optional components such as the formatter and linter. rustup is the tool that downloads, updates, and switches between toolchains, and it is the official way to install Rust.

On Linux or macOS you install rustup with the official script, and on Windows with the installer from rust-lang.org:

bash
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

This installs the stable toolchain for your machine and puts cargo and rustc on your PATH. Verify it:

bash
rustc --version
cargo --version

Typical output prints a version number, a commit hash, and a commit date, for example rustc 1.85.0 (...); the exact numbers depend on the release you installed, and that is fine.

1install and select channels

Rust ships on three channels: stable, beta, and nightly. You can install any of them and set which one is the default:

bash
rustup install stable
rustup install nightly
rustup default stable
rustup toolchain list

rustup toolchain list shows every toolchain you have, for example stable-x86_64-unknown-linux-gnu (default). The suffix after the channel is the . The default triple is your host machine, the machine you are compiling on.

2add a cross-compilation target

To build for a board instead of your host, add that board's target. This is the embedded angle in one command:

bash
rustup target add aarch64-unknown-linux-gnu
rustup target add armv7-unknown-linux-gnueabihf
rustup target add thumbv7em-none-eabihf

The first two are 64-bit and 32-bit ARM Linux boards; the third is a bare-metal Cortex-M target with no operating system. You will use these in later lessons. rustup target list shows all targets, and rustup target list --installed shows the ones you have.

3add components

Components are extra tools that live inside a toolchain. The ones you will reach for throughout this module:

bash
rustup component add clippy rustfmt miri llvm-tools rust-analyzer
  • clippy is the linter, hundreds of extra checks beyond the compiler's own warnings.
  • rustfmt is the formatter, run as cargo fmt.
  • miri is the MIR interpreter, which executes your program and detects undefined behaviour; it needs the nightly channel for its full feature set.
  • llvm-tools provides low-level binaries such as llvm-objdump and llvm-nm for inspecting generated code.
  • rust-analyzer is the language server that powers editor autocompletion and inline errors.

rustup component add also installs the standard library source with rust-src, useful for reading std and for some bare-metal tooling.

rustup also has installation profiles: minimal (compiler and cargo only), default (adds docs, rustfmt, clippy, and more), and complete (everything). To inspect your whole setup at once, run rustup show, which prints the active toolchain, default host, and the overrides in effect.

4pin a toolchain per project

A project that must keep compiling for years should not depend on whatever stable happens to be current. A rust-toolchain.toml file in the project root pins the exact channel, components, and targets:

toml
[toolchain]
channel = "1.85.0"
components = ["rustfmt", "clippy"]
targets = ["aarch64-unknown-linux-gnu"]

When you run any Rust command inside that directory, rustup notices the file, downloads that toolchain if needed, and uses it. A one-line rust-toolchain file with just nightly does the same for the channel. This is how a team guarantees everyone, and every CI machine, builds with the same compiler.

For a machine with no internet, rustup supports an offline install: install on a connected machine, then copy the toolchain's directory and set RUSTUP_HOME and CARGO_HOME to point at the copies. This matters for air-gapped build servers and for building firmware images in a locked-down lab.

Rustup toolchains and componentsrustupstabledefault channelrustccargoclippyrustfmtrust-stdbetapreview of the next releasenightlyunstable featuresmirillvm-toolsrust-srcrustupstabledefault channelrustccargoclippyrustfmtrust-stdbetapreview of the next releasenightlyunstable featuresmirillvm-toolsrust-src
Rustup, its release channels, and the components each toolchain can contain
04

rustc and editions

3 min read

The Rust compiler is rustc. For a single file you can skip Cargo entirely. Put this in main.rs:

rust
fn main() {
    println!("Hello, world!");
}

Compile and run:

bash
rustc main.rs
./main

rustc produces a native binary, main on Linux, the same way gcc or clang produce an executable from C. fn main() is the entry point of every executable program, and println! is a macro, which you can tell by the !. The ! marks a macro invocation, which generates code at compile time rather than being an ordinary function call.

An is Rust's answer to a hard problem: a language used for decades must evolve, but old code must keep compiling. Editions let the two coexist. The edition key in Cargo.toml selects one for your crate, and if the key is absent, rustc assumes edition 2015, the original.

There are four editions: 2015, 2018, 2021, and 2024. Each one ships as part of the normal six-week release process and bundles the changes that accumulated since the last one. An edition can make breaking changes that a simple compiler upgrade cannot, because it can, for example, turn a word that was a variable name into a new keyword. Edition 2018 made async and await keywords. Edition 2021 changed how closures capture variables. Edition 2024 changed lifetime capture in return-position impl Trait and several other details. The full list lives in the Edition Guide.

Two facts make editions safe. First, every compiler version supports every edition that existed when it was released, so old crates never stop compiling when you upgrade rustc. Second, crates of different editions link together freely; an edition changes only how your own source is parsed, not the compiled output. A 2015 crate and a 2024 crate can be dependencies of the same binary.

toml
[package]
name = "hello"
version = "0.1.0"
edition = "2024"

To move an existing crate to a newer edition, edit the key and run cargo fix --edition, which applies the mechanical changes automatically.

Under the hood, rustc runs your source through a fixed pipeline: it parses to an abstract syntax tree, resolves names and types, lowers to an intermediate form called MIR, runs the borrow checker on MIR, hands the result to LLVM for optimisation and code generation, and links a native binary. The borrow checker is the part that enforces the ownership rules you will study in the next lesson; it lives in the compiler and runs at compile time, which is why the safety checks cost you no runtime.

How rustc compiles a programParseAST and HIRType checkresolvenames andtypesMIRborrowcheckerruns hereLLVM IRoptimiseand codegenLinknativeexecutableParseAST and HIRType checkresolvenames andtypesMIRborrowcheckerruns hereLLVM IRoptimiseand codegenLinknativeexecutable
The stages a source file passes through inside rustc
05

Projects with Cargo

4 min read

Cargo is Rust's build system and package manager, and it ships with rustup. Nearly every Rust project uses it. A is what Cargo builds.

Create a project:

bash
cargo new guessing_game
cd guessing_game

cargo new makes a directory with two files and a directory: Cargo.toml, a src/ directory containing main.rs, and a .gitignore. It also initialises a Git repository unless you are already inside one. cargo init does the same thing inside an existing directory, and both take --lib to create a library instead of a binary.

1understand the layout

  • Cargo.toml is the manifest: package metadata and dependencies, written in the TOML format.
  • src/main.rs is the root of a binary crate; src/lib.rs is the root of a library crate. A package can have both, a library plus one or more binaries.
  • Cargo.lock records the exact resolved versions of every dependency; Cargo maintains it, and you never edit it by hand.
  • target/ holds build output: target/debug/ for development builds and target/release/ for optimised ones.

2build, run, and check

bash
cargo build
cargo run
cargo check

cargo build compiles the project and writes the executable to target/debug/. cargo run builds and then runs it in one step. cargo check compiles without producing an executable, which is much faster and is the standard loop while you are editing: run cargo check constantly, and only cargo build or cargo run when you actually want to execute the result.

3test and build docs

bash
cargo test
cargo doc

cargo test runs your unit and integration tests. cargo doc runs rustdoc over your crate and generates HTML documentation in target/doc/; add --open to open it in a browser. Both are part of the same convention-over-configuration design: the commands are identical whether you are on Linux, macOS, or Windows, and whether your project has zero or fifty dependencies.

4the two build profiles

Cargo builds with two profiles by default. The dev profile, used by cargo build, cargo run, and cargo test, optimises for compile speed: no optimisation and full debug info, so it compiles fast and debugs well. The release profile, used by cargo build --release, optimises for runtime speed: heavy optimisation and no debug info, so it compiles more slowly but runs faster. Always benchmark with the release binary in target/release/, never with the dev binary.

You can tune the profiles in the manifest. Here the release profile turns on link-time optimisation:

toml
[profile.release]
opt-level = 3
lto = true

For an embedded product the release profile is also about size: smaller, faster binaries matter when flash and RAM are limited, and the same flags that speed code up often shrink it as well.

Step by stepWhat cargo run actually does
  1. Read the manifest: parse Cargo.toml for the package name, edition, and dependency list.

  2. Resolve versions: pick the newest allowed version of every dependency and write Cargo.lock on the first build.

  3. Fetch and compile dependencies: download any missing crates from the registry and build them.

  4. Compile your crate: build src/main.rs (or src/lib.rs) against those dependencies.

  5. Link and run: link the final binary and execute target/debug/.

A Cargo project layoutmy_projectCargo.tomlmanifestCargo.lockpinned versionssrcmain.rsbinary cratelib.rslibrary cratetargetdebugdev profilereleaseoptimised.gitignoreignores target/my_projectCargo.tomlmanifestCargo.lockpinned versionssrcmain.rsbinary cratelib.rslibrary cratetargetdebugdev profilereleaseoptimised.gitignoreignores target/
The files and directories cargo new creates and what each one is for
06

Variables, mutability, and shadowing

3 min read

In Rust, variables are immutable by default. That is the opposite of C, and it is a deliberate nudge toward the safety story: if a value cannot change, one part of your program cannot surprise another by changing it underneath it.

rust
fn main() {
    let x = 5;
    x = 6; // error: cannot assign twice to immutable variable
}

The let keyword introduces a binding. To make a binding mutable, add mut:

rust
fn main() {
    let mut x = 5;
    x = 6;
    println!("{x}"); // 6
}

is different from mut. Shadowing uses let again, and because it creates a brand new binding, it can even change the type:

rust
fn main() {
    let x = 5;
    let x = x + 1;              // x is 6
    {
        let x = x * 2;          // inner scope: x is 12
        println!("{x}");        // 12
    }
    println!("{x}");            // 6 again, inner binding is gone

    let spaces = "   ";
    let spaces = spaces.len();  // same name, new type
}

Shadowing lets you reuse a simple name as you transform a value, while keeping each intermediate binding immutable. With mut you would be locked to a single type and a single, ever-changing value; with shadowing each let is a fresh, read-only binding.

Type inference means you rarely write a type: let x = 5; infers i32, the default integer type. You annotate when the compiler cannot decide, most often with parse, and you must annotate every function parameter and return type, a deliberate rule that makes function signatures self-documenting and improves error messages.

Going deeperconst vs static, and where each lives

Rust has two ways to name a fixed value that is not a local variable. const is a value inlined at every use site, evaluated at compile time, with no fixed memory address:

rust
const MAX_POINTS: u32 = 100_000;

A const is just a number the compiler pastes in; there is no object to point at. static is different: it names a single object with a fixed address that lives for the whole program:

rust
static GREETING: &str = "hello";

Because a static has one address shared by all threads, mutating it is unsafe, and you must wrap changes in a synchronised type. In safe Rust you reach for static together with atomics or the interior-mutability types you will meet in a later lesson. On a bare-metal target, static mut and atomics are how you manage the small amount of globally shared state a microcontroller has, which is why the distinction between an inlined const and an addressed static matters in practice.

Shadowing through scopeslet x = 5let x = x +1x is 6inner let x= x * 2x is 12 inthis scopescope endsinner xdroppedx is 6againlet x = 5let x = x +1x is 6inner let x= x * 2x is 12 inthis scopescope endsinner xdroppedx is 6again
How shadowing rebinds a variable and how the inner binding ends when its scope closes
07

Scalar and compound types

4 min read

Rust is statically typed: the compiler knows the type of every value at compile time. Types come in two families. Scalar types hold a single value; compound types group several values.

The integer types are signed i8, i16, i32, i64, i128 and unsigned u8, u16, u32, u64, u128, plus the pointer-sized isize and usize, which are 64 bits on a 64-bit machine. An integer literal defaults to i32. Literals can be decimal 98_222, hex 0xff, octal 0o77, binary 0b1111_0000, or a byte b'A' for u8, and a suffix sets the type, as in 57u8. Underscores are visual separators only.

Try it below: toggle signed on and off to watch the same eight bits mean 255 or -1.

-1 in 8-bit two's complement is 0b11111111 = 0xFF; read as unsigned the same bits are 255, which is why 255u8 + 1 wraps to 0 in a release build.

  • value: -1
  • width: 8

The floating-point types are f32 and f64, both IEEE-754, with f64 the default. bool is one byte, and char is four bytes. That last one surprises C programmers: a Rust char is a , not an ASCII byte. 'π' and '本' are valid char values, and std::mem::size_of::<char>() is 4 on every platform, enough for supplementary-plane scalars outside the basic multilingual plane. When you need bytes you use u8; when you need text you use strings, which you will meet in a later lesson.

Going deeperInteger overflow: debug panics, release wraps

Rust gives the same arithmetic two different behaviours depending on the profile. In a debug build, overflow is checked and panics:

rust
fn main() {
    let mut n: u8 = 255;
    n = n + 1; // debug: panics with "attempt to add with overflow"
}

In a release build the checks are omitted for speed, and the value wraps in two's complement: 255 + 1 becomes 0. Relying on that wrap is treated as a bug, so when you genuinely want wrapping, say so with the standard library's method families, which behave the same in both profiles:

rust
let w = 255u8.wrapping_add(1);        // 0, always
let c = 255u8.checked_add(1);         // None
let (v, of) = 255u8.overflowing_add(1); // (0, true)
let s = 255u8.saturating_add(1);      // 255, clamped

For embedded code that counts ticks or computes checksums, wrapping_add is often exactly the right, explicit, portable behaviour, and it documents your intent in a way a bare + never does.

The compound types are tuples and arrays. A tuple groups a fixed number of values of possibly different types:

rust
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    let (x, y, z) = tup;   // destructure
    println!("{} {} {}", x, y, z);
    println!("{}", tup.0); // index access
}

The empty tuple () is the unit type: the type of the empty tuple, representing no meaningful value and used as the return type of functions that return nothing. Every statement and every function that does not return a real value evaluates to ().

An array [T; N] holds a fixed number of values of one type, all on the stack:

rust
let a: [i32; 5] = [1, 2, 3, 4, 5];
let zeros = [0; 5];       // five zeros
let first = a[0];

A slice, written &[T], is a reference to some contiguous run of elements together with its length, which is known only at runtime. Arrays are for when the count never changes and you want the data on the stack; slices are how borrowed, variable-length data is viewed. You will use slices constantly once you meet references in the next lesson.

Integer types and their sizes8-biti8u816-biti16u1632-biti32u3264-biti64u64128-biti128u128pointerisizeusizesigned / unsigned; integer literalsdefault to i32
The signed and unsigned integer types at each width, with the i32 default marked
08

Functions and control flow

3 min read

Functions are declared with fn, use snake_case names, and can appear in any order. Every parameter needs a type, and a return type follows an arrow:

rust
fn main() {
    let x = plus_one(5);
    println!("{x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1   // no semicolon: this is the return value
}

The distinction between statements and expressions is the heart of Rust's expression-based style. A statement performs an action and returns nothing; let x = 5; is a statement, and in fact its value is (), which is why you cannot write let x = (let y = 5);. An expression evaluates to a value. Blocks are expressions, so this works:

rust
fn main() {
    let y = {
        let x = 3;
        x + 1    // the block evaluates to 4
    };
    println!("{y}"); // 4
}

The same rule makes if an expression that can be assigned, and makes a loop able to hand a value out through break:

rust
fn main() {
    let number = if 3 < 5 { "small" } else { "large" };

    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2;
        }
    };
    println!("{} {}", number, result);
}

A function with no return type returns (), the unit type. The opposite extreme is a :

rust
fn bail(msg: &str) -> ! {
    eprintln!("{msg}");
    std::process::exit(1);
}

The never type ! says this function does not return; loop {} without a break, panic!, and std::process::exit all have type !. Because a value of type ! can never exist, the compiler lets it coerce to any other type, which is why you can use a diverging call in any expression position. Note that ! is stable as a return type, but not yet usable everywhere as a general value type; the long-running never-type stabilisation is still settling some corners.

Control flow covers if, loop, while, and for. An if condition must be exactly a bool; Rust will not convert an integer to a truth value the way C does. Loops support break and continue, and a loop label disambiguates nested loops:

rust
fn main() {
    'outer: loop {
        loop {
            break 'outer;   // exits the labelled loop
        }
    }

    let mut n = 3;
    while n > 0 {
        println!("{n}");
        n -= 1;
    }

    for i in 1..5 {          // 1, 2, 3, 4
        println!("{i}");
    }
    for i in (1..=3).rev() { // 3, 2, 1
        println!("{i}");
    }

    let a = [10, 20, 30];
    for elem in a {
        println!("{elem}");
    }
}

The for loop works over any iterator, not just ranges. This is the idiomatic way to visit a collection: no manual index, no off-by-one, and the compiler generates the same tight loop as hand-written indexing. match, the other big control-flow construct, is the subject of a later lesson; the labs for this lesson keep to if and loops on purpose.

Statements versus expressionsStatementExpressionReturns a valuenoyesEnds withsemicolonyesusually notExamplelet x = 5;5 + 6Used as a valuecannotcan, e.g. anif or block
The difference between statements, which return nothing, and expressions, which yield a value
09

Dependencies, semver, and the lockfile

2 min read

Real programs depend on other crates. The manifest declares them under sections whose names describe when each is used:

toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"

[dependencies]
rand = "0.10.1"

[dev-dependencies]
criterion = "0.5"

[build-dependencies]
cc = "1"

[features]
fastmath = []
  • [dependencies] are needed by the crate itself, at runtime and compile time.
  • [dev-dependencies] are needed only by tests, examples, and benchmarks, never by users of your library.
  • [build-dependencies] are needed only by the optional build.rs script that runs before the main build.
  • [features] declares optional, named feature flags that downstream users can turn on.

The version string after each name is a requirement. Cargo understands , and turns the requirement into a range. 0.10.1 is shorthand for caret ^0.10.1, meaning any version at least 0.10.1 and below 0.11.0. The four common forms:

toml
serde = "1.0.210"      # caret: >=1.0.210, <2.0.0 (the default)
serde = "~1.0.210"     # tilde: >=1.0.210, <1.1.0
serde = "=1.0.210"     # exactly this version
serde = "*"            # any version
serde = ">=1.0, <2.0"  # a hand-written range

The caret has a special rule for 0.x versions, because semver treats every 0.x release as unstable: ^0.10.1 allows up to but not including 0.11.0, and ^0.0.3 allows only up to 0.0.4. The mental model is that the caret pins everything except the leftmost non-zero digit.

The recommended way to add a dependency is cargo add, which edits Cargo.toml and picks a current version for you:

bash
cargo add rand
cargo add serde --features derive
cargo add criterion --dev
cargo remove rand

cargo add rand resolves the newest compatible version and writes the requirement; the number you get depends on the day you run it. cargo update then moves your resolved dependencies to the newest versions still allowed by the manifest, and cargo update -p rand --precise 0.10.2 pins or moves a single crate.

All of this resolution is recorded in Cargo.lock, which pins the exact version of every transitive dependency. The lockfile is what makes a build reproducible: everyone who builds your project gets the same versions. The convention for committing it is simple. For a binary, commit Cargo.lock, because the lockfile pins the exact artifact you ship. For a library, do not commit it; the lockfile of a library is ignored so that the end user's binary resolves its own consistent set. Cargo implements this by default: cargo new (a binary) does not ignore the lockfile, while cargo new --lib adds it to .gitignore.

Going deeperTarget-specific dependencies and building offline

Dependencies can be declared for only some platforms, which is how you use a Linux-only crate in one place and a Windows fallback in another:

toml
[target.'cfg(target_os = "linux")'.dependencies]
inotify = "0.10"

[target.aarch64-unknown-linux-gnu.dependencies]
gpio-cdev = "0.5"

The first form uses a configuration predicate; the second names a concrete target triple. This is the hook you will use in the embedded lessons to pull in the Linux GPIO and I2C crates only when building for the board.

For an air-gapped build machine or a reproducible embedded image, cargo vendor downloads every dependency into a local vendor/ directory:

bash
cargo vendor vendor/

Combined with a .cargo/config.toml that points Cargo at that directory, and cargo build --offline, the whole build runs with no network access. This is how embedded teams pin and archive their exact dependency set for a product's lifetime.

Diagram in production
The caret, tilde, exact, wildcard, and range version specifiers and what each allows
10

Comments, docs, compiler errors, and common mistakes

4 min read

Comments come in three forms. // is a line comment, /* ... */ is a block comment, and block comments nest, so you can comment out code that itself contains block comments. What makes Rust unusual is that comments can be documentation, consumed by the compiler rather than ignored.

/// documents the item that follows it, and //! documents the enclosing module or crate. They contain Markdown, and code blocks inside them become doctests that cargo test runs automatically:

rust
//! A tiny crate for the lesson.

/// Returns the sum of two integers.
///
/// # Examples
///
/// ```
/// let s = add(2, 3);
/// assert_eq!(s, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

cargo doc runs the rustdoc tool over these comments and produces HTML, with the doctests run by cargo test. Documentation that is also tested is a core Rust cultural value: an example that no longer compiles fails the test suite instead of quietly misleading readers.

The second half of this section is reading the compiler. Rust error messages are famously good, and learning to read them is a skill in itself. Consider a missing mut:

rust
fn main() {
    let x = 5;
    x = 6;
}

Typical output (yours will differ in line numbers):

text
error[E0384]: cannot assign twice to immutable variable `x`
 --> src/main.rs:3:5
  |
2 |     let x = 5;
  |         - first assignment to `x`
3 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable
  |
help: consider changing this to be mutable
  |
2 |     let mut x = 5;
  |         +++

Every error has a code such as E0384. The message names the rule, the arrows point at the exact span, and the help section proposes a fix. You can ask for a longer explanation of any code:

bash
rustc --explain E0384

For type problems, the compiler frequently tells you the two mismatched types and where each came from, which turns most errors into a one-line fix. The rust-analyzer language server brings all of this into the editor as you type: red squiggles for errors, greyed-out names for warnings, autocompletion, and jump-to-definition. Install it as a rustup component or an editor extension, and read its inline messages the same way you read the terminal.

Read the first error first

When a build fails with a wall of messages, scroll to the first error. Later errors are often cascading consequences of the first one, and fixing the first line frequently clears the rest. This is true across C, C++, and Rust alike.

From doc comments to rendered docs/// and //!commentsMarkdownand codeexamplescargo docrunsrustdocHTML docswritten totarget/doccargo testruns codeexamples asdoctests/// and //!commentsMarkdownand codeexamplescargo docrunsrustdocHTML docswritten totarget/doccargo testruns codeexamples asdoctests
How doc comments become HTML through cargo doc and run as tests through cargo test

Common mistakes

Symptom: "cannot assign twice to immutable variable". You wrote let x = 5; x = 6;. The cause is the immutability default. The fix is either to add mut when the value genuinely changes, or to shadow with a fresh let x = x + 1; when you are transforming a value and want each step read-only.

Symptom: "type annotations needed" or "mismatched types". The compiler cannot infer a type, usually on parse, or two arms of an if return different types. Diagnose by reading the full message, which names both types. Fix by adding an annotation, as in let n: u32 = input.trim().parse().expect("not a number");, or by making the two arms return the same type.

Symptom: "attempt to add with overflow" panic in a debug run. An arithmetic result exceeded its type's range. Check whether you meant a larger type, or an explicit wrapping, checked, or saturating operation. This is a logic signal, not a compiler bug.

Symptom: "unresolved import" or "cannot find crate". You used a dependency without declaring it, or you forgot use for an item. Diagnose by looking at the error's suggestion, then run cargo add <crate> and add the use line it proposes.

The through-line is the same for all of them: run cargo check after every small change, read the first error, trust the help text, and let cargo fix apply mechanical corrections when it offers to. Professionals treat the compiler as a collaborator that catches mistakes while they are still cheap.

11

Try it

1 min read

Install a toolchain with rustup, add the aarch64-unknown-linux-gnu target and the clippy and rustfmt components, and pin a rust-toolchain.toml in a scratch project. Then work through the lab: create the guessing-game binary crate, pull in the rand crate with cargo add, build a release binary, and fix the deliberate type mismatch using only the compiler's error output and rustc --explain. Follow with the practice pack, which exercises loops, tuples, arrays, shadowing, and const versus static under cargo run. The next lesson builds directly on the ownership model these exercises only touch: Ownership and moves.

Key takeaways

  • Rust gives C and C++ level control with memory and thread safety enforced by the compiler, and no garbage collector.
  • rustup manages multiple toolchains, cross-compilation targets, and components such as clippy, rustfmt, and miri.
  • Editions (2015, 2018, 2021, 2024) let the language evolve without breaking old crates.
  • Cargo is the build system and package manager; Cargo.toml declares dependencies, Cargo.lock pins them.
  • Commit Cargo.lock for binaries but not for libraries.
  • Variables are immutable by default; reach for mut or shadowing deliberately.
  • Integer overflow panics in debug builds and wraps in release builds; use checked, wrapping, or saturating methods.
  • char is a four-byte Unicode scalar value, not a single byte.

Reflect

  1. Explain to a colleague, in two sentences: explain why Rust matters for systems and embedded programming and name the C/C++ bug classes it prevents.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?

On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

Practise this lessonExercises, quiz, interview preparation and spaced review

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close