]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0524.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0524.md
1 A variable which requires unique access is being used in more than one closure
2 at the same time.
3
4 Erroneous code example:
5
6 ```compile_fail,E0524
7 fn set(x: &mut isize) {
8     *x += 4;
9 }
10
11 fn dragoooon(x: &mut isize) {
12     let mut c1 = || set(x);
13     let mut c2 = || set(x); // error!
14
15     c2();
16     c1();
17 }
18 ```
19
20 To solve this issue, multiple solutions are available. First, is it required
21 for this variable to be used in more than one closure at a time? If it is the
22 case, use reference counted types such as `Rc` (or `Arc` if it runs
23 concurrently):
24
25 ```
26 use std::rc::Rc;
27 use std::cell::RefCell;
28
29 fn set(x: &mut isize) {
30     *x += 4;
31 }
32
33 fn dragoooon(x: &mut isize) {
34     let x = Rc::new(RefCell::new(x));
35     let y = Rc::clone(&x);
36     let mut c1 = || { let mut x2 = x.borrow_mut(); set(&mut x2); };
37     let mut c2 = || { let mut x2 = y.borrow_mut(); set(&mut x2); }; // ok!
38
39     c2();
40     c1();
41 }
42 ```
43
44 If not, just run closures one at a time:
45
46 ```
47 fn set(x: &mut isize) {
48     *x += 4;
49 }
50
51 fn dragoooon(x: &mut isize) {
52     { // This block isn't necessary since non-lexical lifetimes, it's just to
53       // make it more clear.
54         let mut c1 = || set(&mut *x);
55         c1();
56     } // `c1` has been dropped here so we're free to use `x` again!
57     let mut c2 = || set(&mut *x);
58     c2();
59 }
60 ```