Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0503: cannot use `value` because it was mutably borrowed
What it meansA value was used after it was mutably borrowed.
What rustc prints
error[E0503]: cannot use `value` because it was mutably borrowed
--> main.rs:5:16
|
4 | let borrow = &mut value;
| ---------- `value` is borrowed here
5 | let _sum = value + 1; // error: cannot use `value` because
| ^^^^^ use of borrowed `value`
6 | // it was mutably borrowed
7 | println!("{}", borrow);
| ------ borrow later used hereReal 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.
The compiler team's explanation
A value was used after it was mutably borrowed.
Erroneous code example:
fn main() {
let mut value = 3;
// Create a mutable borrow of `value`.
let borrow = &mut value;
let _sum = value + 1; // error: cannot use `value` because
// it was mutably borrowed
println!("{}", borrow);
}
In this example, value is mutably borrowed by borrow and cannot be used to calculate sum. This is not possible because this would violate Rust's mutability rules.
You can fix this error by finishing using the borrow before the next use of the value:
fn main() {
let mut value = 3;
let borrow = &mut value;
println!("{}", borrow);
// The block has ended and with it the borrow.
// You can now use `value` again.
let _sum = value + 1;
}
Or by cloning value before borrowing it:
fn main() {
let mut value = 3;
// We clone `value`, creating a copy.
let value_cloned = value.clone();
// The mutable borrow is a reference to `value` and
// not to `value_cloned`...
let borrow = &mut value;
// ... which means we can still use `value_cloned`,
let _sum = value_cloned + 1;
// even though the borrow only ends here.
println!("{}", borrow);
}
For more information on Rust's ownership system, take a look at the References & Borrowing section of the Book.
From rustc --explain E0503 (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
- E0501cannot borrow `*a` as mutable because previous closure requires unique access
- E0505cannot move out of because it is borrowed
- E0506cannot assign to because it is borrowed
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?