Skip to main content

Variables and mutability

A `let` binding in Rust is immutable unless you say otherwise. That is the opposite default to most languages, and it is deliberate: a value that never changes cannot be changed by accident from the other side of the program.

Adding `mut` is a promise you make in the source, so anyone reading the code — including you in six months — can see exactly which values move underneath them.

Types are inferred, but they are still static. Once the compiler decides `count` is an `i32`, it stays an `i32` for the whole binding.

Forgetting `mut`

fn main() {
    let count = 0;
    count += 1; // error[E0384]
}

error[E0384]: cannot assign twice to immutable variable `count`

Write `let mut count = 0;`. If the value genuinely should not change, keep it immutable and compute a new binding instead.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust