Variables and Mutability

Variables and Mutability in Rust: Think of a variable as a desk in an office, with a small name plate on it.

The Analogy: The Desk With a Name Plate

Think of a variable as a desk in an office, with a small name plate on it. When you write let count = 0; you are doing two separate things: putting a value at a fresh desk, and hanging a plate reading count on that desk. From then on, saying "count" means "whatever is at the desk this plate is on". Most languages blur these two acts together. Rust keeps them distinct, and almost everything surprising about variables in Rust falls out of that distinction.

The details on the desk are written in ink. You can walk over and read them as often as you like, but you cannot alter them. If you want a desk whose occupant can be edited, you must say so when you set it up: let mut count = 0; hands out a pencil instead of a pen. This is the reverse of the default in C, Java, Python, and JavaScript, where everything is editable unless you go out of your way, and it is not a stylistic preference. Because the compiler knows which desks are pencil desks, it can reason about who might be changing what, which is the foundation the borrow checker is built on two lessons from now.

Now the part that trips up everyone arriving from another language. You are allowed to write let count = ...; a second time with the same name. This is not an error, and it is not assignment. It sets up a brand new desk, puts a new value at it, and moves the name plate over. The original desk and its original occupant are still there, in the room, holding their original ink-written value; they have simply become unreachable, because the only way you had to refer to them was that plate. This is called shadowing, and because the second desk is genuinely a different desk, it may hold a completely different type of thing.

Constants are a different arrangement altogether. const MAX_RETRIES: u32 = 3; is not a desk at all: it is a fact engraved into the building's foundation stone. There is nothing to point a plate at, because the compiler simply writes 3 into every place your code said MAX_RETRIES. It follows that a constant must be computable before the building opens, it can never be edited, and asking for its address is a category error rather than a permission problem.


Syntax or Core Structure

All four arrangements in one program:

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

    let mut y = 5;
    y = 6;
    println!("y = {y}");

    let spaces = "   ";
    let spaces = spaces.len();
    println!("spaces = {spaces}");

    let z = 10;
    {
        let z = z * 2;
        println!("inner z = {z}");
    }
    println!("outer z = {z}");

    const MAX_RETRIES: u32 = 3;
    println!("MAX_RETRIES = {MAX_RETRIES}");
}

Output:

x = 5
y = 6
spaces = 3
inner z = 20
outer z = 10
MAX_RETRIES = 3

The spaces pair is the one to stare at. The first spaces is a &str; the second is a usize. Shadowing changed the type of what that name refers to, in the same scope, with no cast and no new name invented. The z pair shows the other axis: the inner let z shadows only within its block, so the outer z is intact on the line after the closing brace, still 10.

Try to reassign an immutable binding and the compiler is specific about it:

let x = 5;
x = 6;

Output (trimmed):

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 making this binding mutable
  |
2 |     let mut x = 5;
  |         +++

The line and column numbers are from one particular file, but the shape is universal: Rust points at the first assignment, points at the second, and then writes the fix out for you. Getting into the habit of reading down to the help: line saves an enormous amount of time in the first week.


Technical Depth: Four Ways to Name a Value

Shadowing is not mutation

These two lines look similar and mean genuinely different things.

let mut x = 1; x = 2;let x = 1; let x = 2;
number of bindingsonetwo
needs mutyesno
may change typenoyes
the old valueoverwritten and gonestill exists, merely unnameable
after the second line, can x change again?yes, anywhere x is in scopeonly by another let
how a reader must verify the valuescan the rest of the scope for assignmentsread the most recent let

That last row is the practical argument for shadowing. With mut, knowing what x holds at line 40 requires checking every line between. With shadowing, every binding is assigned exactly once, so the nearest let above is the whole answer. Semantically the second form creates a new binding; whether the optimiser reuses the same stack slot is its business, not yours.

let, const, and static

letconststatic
computedat run timeat compile timeat compile time
type annotationoptionalrequiredrequired
has one fixed addressyes, a stack slotno, it is inlined at every useyes, exactly one in the binary
can be mutablewith mutneveronly via unsafe and static mut
lifetimeits scopenone of its own'static
conventionsnake_caseSCREAMING_SNAKESCREAMING_SNAKE
allowed inside a functionyesyesyes

The address row explains a rule that otherwise looks arbitrary. Because a const is substituted at each use site, &MAX_RETRIES in two places may give two different addresses, and comparing those addresses is meaningless. A static is one object in the binary's data section, so its address is stable and unique. Reach for const for plain values and static only when you specifically need a single shared object, such as a large lookup table you do not want duplicated.

Avoid static mut entirely. Every access needs unsafe because nothing prevents two threads from touching it, and on the 2024 edition taking a reference to one is a hard error rather than a warning. The modern replacements are AtomicUsize and friends for counters, Mutex or RwLock for anything larger, and OnceLock for a value initialised once on first use.

What the compiler infers, and when you must say

Rust infers the type of almost every binding, but it has defaults it falls back on and cases where it refuses to guess.

WrittenInferredNote
let n = 5;i32the default integer, chosen when nothing else constrains it
let f = 2.5;f64the default float
let c = 'x';charfour bytes, one Unicode scalar value, not one byte
let s = "hi";&'static stra borrowed view of text baked into the binary
let v = vec![1u8, 2];Vec<u8>the suffix on the first element decides it
let v = Vec::new();errornothing in that line says what it holds

The last row is worth internalising, because the error message names the problem precisely: type annotations needed. Two things can fix it, an annotation on the left (let v: Vec<u8> = Vec::new();) or a later line that pushes a u8 into it. Inference in Rust flows through a whole function body, not just the current statement, which is why moving one line can make an annotation unnecessary. When you want to state the type at the call site instead, the turbofish does it: "42".parse::<u8>().

Initialise later, without mut

A binding may be declared and assigned on a later line, as long as the compiler can prove it is assigned exactly once before use on every path.

fn main() {
    let score = 87;
    let label: &str;

    if score >= 90 {
        label = "excellent";
    } else if score >= 70 {
        label = "good";
    } else {
        label = "needs work";
    }

    println!("{score} is {label}");
}

Output:

87 is good

There is no mut there, and none is needed: three branches, one assignment on each. Delete the final else and the compiler rejects the println! with E0381: used binding is possibly-uninitialized, because now a path exists where label never got a value. This analysis is called definite initialisation, and it is the reason Rust has no concept of a null or default-initialised local.

let ... else for the early exit

Since Rust 1.65 a let can carry a fallback block, which must diverge:

fn parse_port(raw: &str) -> u16 {
    let Ok(port) = raw.parse::<u16>() else {
        return 8080;
    };
    port
}

The win is that port is in scope for the rest of the function rather than only inside a nested block, which keeps the happy path unindented. The else block has to end the current path with return, break, continue, or a panic; the compiler will not accept one that falls through.

_ and _name are not the same thing

let _ = compute();        // value is dropped at the end of this statement
let _unused = compute();  // value is bound, and dropped at the end of the scope

_ is a wildcard pattern that binds nothing, so the value it discards is destroyed immediately. _unused is a real binding whose name merely starts with an underscore to silence the unused-variable warning, so the value lives until the scope ends. The classic bug this creates is let _ = mutex.lock();, which acquires the lock and releases it on the same line, leaving the "protected" code completely unprotected. let _guard = mutex.lock(); is what you meant.


Real World Example: Turning Raw Configuration Into Typed Settings

Configuration always arrives as text, and it always needs to end up as numbers, flags, and bounded values. That journey is what shadowing is for, and the following program is the shape you will write over and over.

fn main() {
    // Values as they arrive, e.g. from environment variables or a file.
    let raw_port = "  8080  ";
    let raw_workers = "128";
    let raw_verbose = "true";

    // One concept, refined in stages, immutable at every stage.
    let raw_port = raw_port.trim();
    let port: u16 = raw_port.parse().expect("port must be a number");

    let workers: usize = raw_workers.parse().expect("workers must be a number");
    let workers = workers.clamp(1, 64);

    let verbose = matches!(raw_verbose, "1" | "true" | "yes");

    const DEFAULT_TIMEOUT_SECS: u64 = 30;
    let timeout_secs = if verbose {
        DEFAULT_TIMEOUT_SECS * 2
    } else {
        DEFAULT_TIMEOUT_SECS
    };

    // Genuine accumulation: this one earns its `mut`.
    let mut summary = String::new();
    summary.push_str("listening on port ");
    summary.push_str(&port.to_string());

    println!("{summary}");
    println!("workers      = {workers}");
    println!("verbose      = {verbose}");
    println!("timeout_secs = {timeout_secs}");
}

Output:

listening on port 8080
workers      = 64
verbose      = true
timeout_secs = 60

Look at how the names are chosen. raw_port is shadowed once, because trimming whitespace does not change what the value is: it is still the text that arrived, just tidier. The moment the meaning changes, from "text that arrived" to "a validated port number", the name changes too, and port is a fresh binding of type u16. That is the discipline worth copying: shadow when refining a stage of one concept, rename when the concept itself changes. The reward is that no name in the program ever lies about what it holds.

The workers pair shows shadowing earning its keep, and the output proves it did something: 128 went in and 64 came out. Note what a reader has to do to be sure of that. There is no mut anywhere in the chain, so every one of these bindings is assigned exactly once, and the value of workers at the bottom of the function is fully determined by the last let workers above it. Had this been let mut workers with a later workers = workers.clamp(1, 64);, the same reader would have to scan every intervening line to rule out another assignment. Also notice that clamp returns a new value rather than editing one in place, which is the standard shape for this family of helpers.

const DEFAULT_TIMEOUT_SECS sits inside main because constants are items and items may be declared in any block. Scoping it to the one function that uses it keeps it out of the crate's namespace entirely, which is a small win worth taking. Both mentions of the name are replaced by 30 during compilation, and DEFAULT_TIMEOUT_SECS * 2 folds to 60 before the program ever runs. The if/else is doing something else worth naming: in Rust if is an expression, so the whole conditional evaluates to a value and is bound in one let. This is why idiomatic Rust rarely contains the declare-then-conditionally-reassign pattern that mut would require in C or Java.

Exactly one binding in the program is mut, and it is the one that genuinely changes over time: a string being accumulated across three statements. That is the signal to aim for. When mut is rare, its presence tells a reviewer where the moving parts are; when it is everywhere, it tells them nothing. One last detail hides in &port.to_string(): to_string() produces an owned String, the & makes it a &String, and the compiler quietly converts that to the &str that push_str expects. That conversion is called deref coercion, and the Mastering Strings lesson is where it stops being magic.


Common Mistakes

  1. Adding mut to make an error go away. cannot assign twice to immutable variable is often better answered with a second let than with mut. Ask whether the value genuinely changes over time or whether you are simply computing the next stage of it.
  2. Believing shadowing is assignment. let x = x + 1; inside a loop body does not accumulate across iterations, because each pass creates a new binding from the outer one. If you want accumulation, you want mut.
  3. Shadowing across a type change and keeping the same name anyway. Legal, and occasionally awful. let user = user.id; compiles and leaves a reader convinced that user is still a user.
  4. Expecting const to have an address. &MAX in two places may produce two different addresses because the value is inlined at each use. If you need one shared object, that is what static is for.
  5. Omitting the type on a const or static. Both require an explicit annotation; only let may lean on inference. The error is immediate, but it surprises people who expect symmetry.
  6. Reaching for static mut. Every touch requires unsafe, nothing guards it against threads, and taking a reference to one is a hard error on the 2024 edition. Use AtomicUsize, Mutex, or OnceLock instead.
  7. Writing let _ = guard.lock();. The _ pattern binds nothing, so the guard drops at the end of that statement and the lock is released before the code it was supposed to protect. Bind it to _guard instead.
  8. Assuming let x; needs mut to be filled in later. Deferred initialisation is allowed without mut as long as exactly one assignment happens on every path, which is often cleaner than a placeholder value.
  9. Fighting type annotations needed with a cast. The compiler is not asking you to convert anything; it is telling you that nothing in the function pins the type down. An annotation on the let, or a turbofish at the call, is the fix.

Best Practices

  • Reach for mut only when a value genuinely changes over its lifetime. Buffers being filled and counters being incremented qualify; a value being computed in three steps does not.
  • Use shadowing for the stages of one concept, and a new name when the concept changes. let raw = raw.trim(); is clear. let user = user.id; is a trap.
  • Annotate the binding at the point where text becomes data. let port: u16 = raw.parse()?; documents the contract and lets parse pick its implementation from the annotation.
  • Prefer const for plain values, and scope it to the smallest block that needs it. Constants are items, so a function-local const is entirely normal and keeps the crate namespace clean.
  • Let if, match, and blocks produce values instead of assigning into a pre-declared variable. One let bound to an expression beats let mut followed by branches that overwrite it.
  • Bind guards and other drop-sensitive values to a real name. _guard for "I need this alive but will not touch it", _ only for "destroy this now".
  • Keep the naming conventions. snake_case for bindings, SCREAMING_SNAKE for const and static; cargo clippy will tell you when you have slipped, and consistency here makes unfamiliar code readable at a glance.
  • Treat clippy::needless_late_init and friends as free code review. Clippy has a whole family of lints about bindings, and each one comes with an explanation of the idiom it is steering you toward.

Practice Exercises

  1. Prove the desks are different. Write a program that binds let value = "42"; then shadows it with let value = value.parse::<i32>().unwrap(); and finally with let value = value * 2;. Print the value after each step, and add a comment above each let naming the type at that point.
  2. Find the accumulation bug. Write a loop that tries to sum 1..=5 using let total = total + n; inside the body. Explain in one sentence why the result is wrong, then fix it two ways: once with mut, and once with an iterator method that needs no mutable binding at all.
  3. Trigger definite initialisation. Write a function that declares let category: &str; and assigns it in three branches of an if/else if/else. Confirm it compiles without mut, then delete the final else and record the exact error code and message you get.
  4. Demonstrate the underscore trap. Build a small struct whose Drop implementation prints a message, then create one with let _ = MyStruct; and another with let _kept = MyStruct;, printing a marker line between them. Use the order of the printed lines to explain what _ actually did.