error[E0596]: cannot borrow as mutable, as it is not declared as mutable
You called something that changes a value, but the variable (or the reference you hold) is read-only. Variables in Rust are immutable unless you declare them with mut.
Quick fix: Add mut to the let binding, or change a &T parameter to &mut T.
Code that triggers E0596
fn main() {
let names = Vec::new();
names.push("Ferris");
println!("{names:?}");
}What the compiler says
error[E0596]: cannot borrow `names` as mutable, as it is not declared as mutable
--> src/main.rs:3:5
|
3 | names.push("Ferris");
| ^^^^^ cannot borrow as mutable
|
help: consider changing this to be mutable
|
2 | let mut names = Vec::new();
| +++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0596`.Why Rust raises E0596
Vec::push takes &mut self, so calling it needs a mutable borrow of names. A variable declared with plain let can’t be borrowed mutably. The compiler’s help line even shows where the mut goes.
The same code has a different ending when you only hold a shared reference. Here names is a &Vec<String>, which can only read:
fn add_name(names: &Vec<String>) {
names.push(String::from("Ferris"));
}
fn main() {
let names = Vec::new();
add_name(&names);
println!("{names:?}");
}error[E0596]: cannot borrow `*names` as mutable, as it is behind a `&` reference
--> src/main.rs:2:5
|
2 | names.push(String::from("Ferris"));
| ^^^^^ `names` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
1 | fn add_name(names: &mut Vec<String>) {
| +++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0596`.How to fix E0596
1. Declare the variable with mut
Mutability is opt-in. Add mut where the variable is declared.
fn main() {
let mut names = Vec::new();
names.push("Ferris");
println!("{names:?}");
}2. Take &mut in functions that change their argument
A function that modifies its argument needs a mutable reference, and the caller passes &mut names. The mut on the caller’s variable is required too.
fn add_name(names: &mut Vec<String>) {
names.push(String::from("Ferris"));
}
fn main() {
let mut names = Vec::new();
add_name(&mut names);
println!("{names:?}");
}Related errors
- E0594: cannot assign, as it is not declared as mutable
- E0384: cannot assign twice to immutable variable
- E0502: cannot borrow as mutable because it is also borrowed as immutable
Learn the concept behind it
The References and Borrowing lesson explains the rules behind E0596 with diagrams and more examples. For the official reference, run rustc --explain E0596 or read the E0596 entry in the Rust error index .
Hit a different error? Paste it into the Rust error lookup to find its fix.