1 A mutable variable is used but it is already captured by a closure.
3 Erroneous code example:
6 fn inside_closure(x: &mut i32) {
7 // Actions which require unique access
10 fn outside_closure(x: &mut i32) {
11 // Actions which require unique access
18 outside_closure(a); // error: cannot borrow `*a` as mutable because previous
19 // closure requires unique access.
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.
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.
32 [capturing]: https://doc.rust-lang.org/stable/rust-by-example/fn/closures/capture.html
34 To fix this error, you can finish using the closure before using the captured
38 fn inside_closure(x: &mut i32) {}
39 fn outside_closure(x: &mut i32) {}
46 // borrow on `a` ends.
47 outside_closure(a); // ok!
51 Or you can pass the variable as a parameter to the closure:
54 fn inside_closure(x: &mut i32) {}
55 fn outside_closure(x: &mut i32) {}
58 let mut bar = |s: &mut i32| {
66 It may be possible to define the closure later:
69 fn inside_closure(x: &mut i32) {}
70 fn outside_closure(x: &mut i32) {}