← Fundamentals
Fundamentals

Rust let, mut, and shadowing

Why is a Rust binding immutable unless marked mut, and how is shadowing different from mutation?

Distinguish changing a Rust binding from introducing a new one.

Outcome

Say what a binding without mut forbids, use shadowing to change a value’s form, tell a new binding inside a block, loop or match arm from an assignment to the outer one, and repair code that confuses the two.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Binding
A name introduced by let, a function parameter or a pattern, attached to a value.
mut
Permits reassignment of an initialized local and mutable access to owned data where the borrow rules allow it. It does not turn an existing & reference into &mut.
Shadowing
Declaring a new binding with a name already in use; the earlier binding is hidden, not changed.
Block expression
A { … } whose last expression without a semicolon is its value.
Match guard
An if condition after a pattern that must also hold for the arm to match.

Bindings, permission and scope

Rust’s let introduces a binding. mut grants permission to reassign an initialized local and to use mutable access where ownership and borrowing allow it. Another let introduces a new binding, even when it reuses a spelling already in scope; this is shadowing.

Scope determines where that replacement name is visible. Initializers can read an earlier binding, and patterns can introduce names of their own. To explain a change, identify the declaration each occurrence refers to before deciding whether an outer value was updated.

01let without mut

A binding without mut cannot be assigned again

A fish-market dispatch command records crate arrivals, prepares weight slips and prints a fixed-price crate bill. An extra arrival must update the retained count; a weight preview must leave its gross measurement available. When the code repeats a name, is it updating that retained value or creating a local replacement?

The dispatch counter already holds three arrivals. Another crate arrives, and the command tries to replace the retained count with four. Predict what rustc does with the initialized binding.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let crates = 3;

    println!("crates {crates}");

    crates = crates + 1;

    println!("crates {crates}");
}
What happens when you compile it?
Rust · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
rustc main.rs && ./main

Use the Rust setup from the first reading and replace main.rs for each complete experiment. Imports and entry points are included.

02Shadowing

A second let makes a new binding with the same name

An entered batch count includes spaces. The command needs its numeric value before adding three newly arrived crates. The source reuses crates while moving from owned text to trimmed text and then a u32. Predict whether each let preserves the previous binding or changes its type in place.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let crates = String::from(" 12 ");
    let crates = crates.trim();
    let crates: u32 = crates.parse().unwrap();

    println!("{}", crates + 3);
}
What is printed?

03Blocks

A let inside a block ends at its closing brace

The next diagnostic retains a gross weight of 2200 g. A local calculation removes the 300 g ice allowance to display complete net kilograms. For a heavy crate it also logs a proposed 1000 g reduction, without saving that preview as the gross measurement. Predict which grams each local operation reads and what the final line retains.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let grams = 2200;

    let kilos = {
        let grams = grams - 300;
        grams / 1000
    };

    if grams > 2000 {
        let grams = grams - 1000;

        println!("inside {grams}");
    }

    println!("{grams} {kilos}");
}
What are the two lines?

04Match arms

Does the special pattern compare with the selected special?

Staff select a fish kind as the daily special before pricing the crate bill. The reduced label helper receives that runtime choice as its special parameter. Its match arm repeats the parameter’s name. Does it compare with that selected value, or introduce another binding? Predict both labels.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn label(fish: &str, special: &str) -> &'static str {
    match fish {
        special => "special",
        _ => "regular",
    }
}

fn main() {
    println!(
        "{} {}",
        label("cod", "mackerel"),
        label("mackerel", "mackerel")
    );
}
What is printed?

05Repair the fish market

A crate total, ice-free weights, then a bill

Complete the dispatch command with fresh input records. First sum every crate’s grams. Next return net grams for fresh crates while preserving dried weights; a fresh crate includes the standard 300 g of ice. Finally price crate lines using the selected special and carry a running total between rows. A correct price on one row is insufficient to verify that total.

This lab is Rust-only. Each file contains its imports, reader and complete caller.

Repair the fish market

Retained weight totals, fresh-or-dried net slips, then crate prices and a running bill.

  1. easy · F-SHADOW-V4-1 Total the crates
  2. medium · F-SHADOW-V4-2 Weigh without the ice
  3. hard · F-SHADOW-V4-3 Bill the special
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.