]> git.lizzy.rs Git - rust.git/blob - src/librustc_error_codes/error_codes/E0501.md
Spell check librustc_error_codes
[rust.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
7 http://rustbyexample.com/fn/closures/capture.html for more information about
8 capturing.
9
10 Erroneous code example:
11
12 ```compile_fail,E0501
13 fn inside_closure(x: &mut i32) {
14     // Actions which require unique access
15 }
16
17 fn outside_closure(x: &mut i32) {
18     // Actions which require unique access
19 }
20
21 fn foo(a: &mut i32) {
22     let mut bar = || {
23         inside_closure(a)
24     };
25     outside_closure(a); // error: cannot borrow `*a` as mutable because previous
26                         //        closure requires unique access.
27     bar();
28 }
29 ```
30
31 To fix this error, you can finish using the closure before using the captured
32 variable:
33
34 ```
35 fn inside_closure(x: &mut i32) {}
36 fn outside_closure(x: &mut i32) {}
37
38 fn foo(a: &mut i32) {
39     let mut bar = || {
40         inside_closure(a)
41     };
42     bar();
43     // borrow on `a` ends.
44     outside_closure(a); // ok!
45 }
46 ```
47
48 Or you can pass the variable as a parameter to the closure:
49
50 ```
51 fn inside_closure(x: &mut i32) {}
52 fn outside_closure(x: &mut i32) {}
53
54 fn foo(a: &mut i32) {
55     let mut bar = |s: &mut i32| {
56         inside_closure(s)
57     };
58     outside_closure(a);
59     bar(a);
60 }
61 ```
62
63 It may be possible to define the closure later:
64
65 ```
66 fn inside_closure(x: &mut i32) {}
67 fn outside_closure(x: &mut i32) {}
68
69 fn foo(a: &mut i32) {
70     outside_closure(a);
71     let mut bar = || {
72         inside_closure(a)
73     };
74     bar();
75 }
76 ```