error[E0499]: cannot borrow as mutable more than once at a time
You created a second mutable reference (&mut) to a value while the first one was still in use. Rust allows only one mutable reference to a value at a time.
Quick fix: Finish using the first &mut before creating the second one, or split the data into parts that don’t overlap.
Code that triggers E0499
fn main() {
let mut log = String::from("start");
let a = &mut log;
let b = &mut log;
a.push_str(" -> step one");
b.push_str(" -> step two");
println!("{log}");
}What the compiler says
error[E0499]: cannot borrow `log` as mutable more than once at a time
--> src/main.rs:4:13
|
3 | let a = &mut log;
| -------- first mutable borrow occurs here
4 | let b = &mut log;
| ^^^^^^^^ second mutable borrow occurs here
5 | a.push_str(" -> step one");
| - first borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0499`.Why Rust raises E0499
Both a and b point mutably at log, and both are used afterwards. If two mutable references could coexist, one could reallocate the string while the other was still writing into the old buffer. That’s a data race, even in single-threaded code, and Rust’s one-writer rule rules it out at compile time.
As with every borrow, overlap is what matters: a stays alive until line 5, its last use, and b is created on line 4, before that.
How to fix E0499
1. Use one mutable borrow at a time
Finish with a before you create b. Since non-lexical lifetimes arrived in Rust 2018, a borrow ends at its last use, so you don’t need extra braces.
fn main() {
let mut log = String::from("start");
let a = &mut log;
a.push_str(" -> step one");
let b = &mut log;
b.push_str(" -> step two");
println!("{log}");
}2. Split the data into parts that don’t overlap
If you need to change two parts of the same collection at the same time, ask for two separate halves. split_at_mut returns two &mut slices that the compiler knows can’t overlap. Mutably borrowing two different fields of a struct at once works too.
fn main() {
let mut scores = [10, 20, 30, 40];
let (left, right) = scores.split_at_mut(2);
left[0] += 1;
right[0] += 1;
println!("{scores:?}");
}Related errors
- E0502: cannot borrow as mutable because it is also borrowed as immutable
- E0596: cannot borrow as mutable, as it is not declared as mutable
- E0382: borrow of moved value
Learn the concept behind it
The References and Borrowing lesson explains the rules behind E0499 with diagrams and more examples. For the official reference, run rustc --explain E0499 or read the E0499 entry in the Rust error index .
Hit a different error? Paste it into the Rust error lookup to find its fix.