]> git.proxmox.com Git - rustc.git/blob - src/librustc_error_codes/error_codes/E0501.md
New upstream version 1.43.0+dfsg1
[rustc.git] / src / librustc_error_codes / error_codes / E0501.md
1 This error indicates that a mutable variable is being used while it is still
2 captured by a closure. Because the closure has borrowed the variable, it is not
3 available for use until the closure goes out of scope.
4
5 Note that a capture will either move or borrow a variable, but in this
6 situation, the closure is borrowing the variable. Take a look at the chapter
7 on [Capturing][capturing] in Rust By Example for more information.
8
9 [capturing]: https://doc.rust-lang.org/stable/rust-by-example/fn/closures/capture.html
10
11 Erroneous code example:
12
13 ```compile_fail,E0501
14 fn inside_closure(x: &mut i32) {
15 // Actions which require unique access
16 }
17
18 fn outside_closure(x: &mut i32) {
19 // Actions which require unique access
20 }
21
22 fn foo(a: &mut i32) {
23 let mut bar = || {
24 inside_closure(a)
25 };
26 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
27 // closure requires unique access.
28 bar();
29 }
30 ```
31
32 To fix this error, you can finish using the closure before using the captured
33 variable:
34
35 ```
36 fn inside_closure(x: &mut i32) {}
37 fn outside_closure(x: &mut i32) {}
38
39 fn foo(a: &mut i32) {
40 let mut bar = || {
41 inside_closure(a)
42 };
43 bar();
44 // borrow on `a` ends.
45 outside_closure(a); // ok!
46 }
47 ```
48
49 Or you can pass the variable as a parameter to the closure:
50
51 ```
52 fn inside_closure(x: &mut i32) {}
53 fn outside_closure(x: &mut i32) {}
54
55 fn foo(a: &mut i32) {
56 let mut bar = |s: &mut i32| {
57 inside_closure(s)
58 };
59 outside_closure(a);
60 bar(a);
61 }
62 ```
63
64 It may be possible to define the closure later:
65
66 ```
67 fn inside_closure(x: &mut i32) {}
68 fn outside_closure(x: &mut i32) {}
69
70 fn foo(a: &mut i32) {
71 outside_closure(a);
72 let mut bar = || {
73 inside_closure(a)
74 };
75 bar();
76 }
77 ```