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