Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0500: closure requires unique access to `*jon_snow` but it is already borrowed
What it meansA borrowed variable was used by a closure.
What rustc prints
error[E0500]: closure requires unique access to `*jon_snow` but it is already borrowed
--> main.rs:3:18
|
2 | let nights_watch = &jon_snow;
| --------- borrow occurs here
3 | let starks = || {
| ^^ closure construction occurs here
4 | *jon_snow = 3; // error: closure requires unique access to `jon_snow`
| --------- second borrow occurs due to use of `*jon_snow` in closure
...
7 | println!("{}", nights_watch);
| ------------ first 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 borrowed variable was used by a closure.
Erroneous code example:
fn you_know_nothing(jon_snow: &mut i32) {
let nights_watch = &jon_snow;
let starks = || {
*jon_snow = 3; // error: closure requires unique access to `jon_snow`
// but it is already borrowed
};
println!("{}", nights_watch);
}
In here, jon_snow is already borrowed by the nights_watch reference, so it cannot be borrowed by the starks closure at the same time. To fix this issue, you can create the closure after the borrow has ended:
fn you_know_nothing(jon_snow: &mut i32) {
let nights_watch = &jon_snow;
println!("{}", nights_watch);
let starks = || {
*jon_snow = 3;
};
}
Or, if the type implements the Clone trait, you can clone it between closures:
fn you_know_nothing(jon_snow: &mut i32) {
let mut jon_copy = jon_snow.clone();
let starks = || {
*jon_snow = 3;
};
println!("{}", jon_copy);
}From rustc --explain E0500 (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
- E0496lifetime name `'a` shadows a lifetime name that is already in scope
- E0501cannot borrow `*a` as mutable because previous closure requires unique access
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?