Rust errors / Everything else
Rust compiler error · checked with rustc 1.99.0
Rust error E0524: two closures require unique access to `*x` at the same time
What it meansA variable which requires unique access is being used in more than one closure at the same time.
What rustc prints
error[E0524]: two closures require unique access to `*x` at the same time
--> main.rs:7:18
|
6 | let mut c1 = || set(x);
| -- - first borrow occurs due to use of `*x` in closure
| |
| first closure is constructed here
7 | let mut c2 = || set(x); // error!
| ^^ - second borrow occurs due to use of `*x` in closure
| |
| second closure is constructed here
...
10 | c1();
| -- 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 variable which requires unique access is being used in more than one closure at the same time.
Erroneous code example:
fn set(x: &mut isize) {
*x += 4;
}
fn dragoooon(x: &mut isize) {
let mut c1 = || set(x);
let mut c2 = || set(x); // error!
c2();
c1();
}
To solve this issue, multiple solutions are available. First, is it required for this variable to be used in more than one closure at a time? If it is the case, use reference counted types such as Rc (or Arc if it runs concurrently):
use std::rc::Rc;
use std::cell::RefCell;
fn set(x: &mut isize) {
*x += 4;
}
fn dragoooon(x: &mut isize) {
let x = Rc::new(RefCell::new(x));
let y = Rc::clone(&x);
let mut c1 = || { let mut x2 = x.borrow_mut(); set(&mut x2); };
let mut c2 = || { let mut x2 = y.borrow_mut(); set(&mut x2); }; // ok!
c2();
c1();
}
If not, just run closures one at a time:
fn set(x: &mut isize) {
*x += 4;
}
fn dragoooon(x: &mut isize) {
{ // This block isn't necessary since non-lexical lifetimes, it's just to
// make it more clear.
let mut c1 = || set(&mut *x);
c1();
} // `c1` has been dropped here so we're free to use `x` again!
let mut c2 = || set(&mut *x);
c2();
}From rustc --explain E0524 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0061this function takes N arguments but M were supplied
- E0412cannot find type in this scope
- E0515cannot return reference to local variable
- E0728await is only allowed inside async functions and blocks
- E0514Dependency compiled with different version of `rustc`
- E0570The requested ABI is unsupported by the current target
- E0571`break` with value from a `while` loop
Up next
Often hit nextE0061: this function takes N arguments but M were suppliedA related error from the same family.Read it next →Did this answer your question?