Error E0596

"cannot borrow as mutable, as it is not declared as mutable" — How to Fix

This error occurs because you are attempting to mutate a variable that was declared as immutable, which Rust enforces by default.

This error occurs because you are attempting to mutate a variable that was declared as immutable, which Rust enforces by default. To fix it, simply add the mut keyword to the variable's declaration or the binding pattern where it is defined.

Here is a common scenario where this happens when trying to modify a value:

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

To resolve this, declare x as mutable at the point of initialization:

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

This rule also applies strictly to function arguments. If you pass a value into a function and try to change it, the parameter itself must be declared as mut, not just the variable passed in.

fn increment(n: i32) {
    n = n + 1; // Error E0596: cannot borrow `n` as mutable
}

fn main() {
    let val = 10;
    increment(val);
}

Fix the function signature to allow mutation of the parameter:

fn increment(mut n: i32) {
    n = n + 1; // Works
    println!("{}", n);
}

fn main() {
    let val = 10;
    increment(val);
}

A frequent edge case involves destructuring or pattern matching. If you bind a value inside a match or if let statement and intend to mutate it within that scope, the binding must be mutable.

let data = Some(5);

if let Some(x) = data {
    x = 10; // Error E0596: `x` is not declared as mutable
}

Add mut directly to the pattern variable:

let data = Some(5);

if let Some(mut x) = data {
    x = 10; // Works
}

Remember that mut only allows reassignment of the variable binding or mutation of the data if the type supports it (like a Vec or Box). If you are trying to mutate the contents of a reference (e.g., &T), you need a mutable reference (&mut T) instead of just a mutable variable holding an immutable reference.

let mut vec = vec![1, 2, 3];
let first = &vec[0];
*first = 99; // Error: cannot borrow `vec[0]` as mutable because it is behind a `&` reference

In this case, changing the variable to mut doesn't help because the reference itself is immutable. You need to change the reference binding:

let mut vec = vec![1, 2, 3];
let mut first = &mut vec[0]; // Mutable reference
*first = 99; // Works