Mutability (mut) (Rust)

In Rust variables are immutable by default. The mut keyword makes a variable (or a reference) mutable so you can change its value after binding it.

Rust

Writing let x = 5 creates an immutable binding — reassigning or modifying it is a compile error. Add mut (let mut x = 5) to allow change. Defaulting to immutable makes code easier to reason about and catches accidental mutation.

mut also applies to references: &mut T is a mutable (exclusive) borrow. You can only have one &mut reference to a value at a time, which is how Rust prevents data races.

Mutability is distinct from shadowing. Shadowing (let x = x + 1) creates a brand-new variable that reuses the name, and can even change the type; mut reuses the same variable and keeps its type.

Syntax

let mut count = 0;
count += 1;

Examples

Rust

fn main() {
    let mut total = 0;
    for i in 1..=3 { total += i; }
    println!("{}", total);
}

Output:

6

Learn it in a lesson

See also

Back to the Dictionary