Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0596: cannot borrow as mutable, as it is not declared as mutable
What it meansYou need a mutable borrow of something that is not mutable: a let without mut, or data reached through a shared & reference.
What rustc prints
error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable --> main.rs:4:9 | 4 | let y = &mut x; // error: cannot borrow mutably | ^^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | 3 | let mut x = 1; | +++
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
Why it happens
let v = Vec::new(); v.push(1);- A method takes
&selfbut changes a field (needs&mut self). - A closure that mutates captured state stored in a non-mut binding.
How to fix it
1. Declare it mut
let mut v = Vec::new();
v.push(1);2. Take &mut self
impl Counter {
fn bump(&mut self) { self.n += 1; }
}3. Interior mutability
When shared access must still change something: Cell, RefCell, Mutex, atomics.
use std::cell::Cell;
struct Hits { n: Cell<u32> }
impl Hits { fn hit(&self) { self.n.set(self.n.get() + 1); } }Other wordings of this error
cannot borrow as mutable, as it is not declared as mutable, cannot borrow as mutable, as it is behind a `&` reference, consider changing this to be mutable
The compiler team's explanation
This error occurs because you tried to mutably borrow a non-mutable variable.
Erroneous code example:
let x = 1;
let y = &mut x; // error: cannot borrow mutably
In here, x isn't mutable, so when we try to mutably borrow it in y, it fails. To fix this error, you need to make x mutable:
let mut x = 1;
let y = &mut x; // ok!From rustc --explain E0596 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0382borrow of moved value
- E0499cannot borrow as mutable more than once at a time
- E0502cannot borrow as mutable because it is also borrowed as immutable
- E0106missing lifetime specifier
- E0582binding for associated type `Output` references lifetime `'a`, which does not appear in the trait input types
- E0594cannot assign to `ss.earth`, as `ss` is not declared as mutable
- E0597does not live long enough
- E0621explicit lifetime required in the type of `y`
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?