]>
Commit | Line | Data |
---|---|---|
d9bb1a4e FG |
1 | A borrowed variable was used by a closure. |
2 | ||
3 | Erroneous code example: | |
4 | ||
5 | ```compile_fail,E0500 | |
6 | fn you_know_nothing(jon_snow: &mut i32) { | |
7 | let nights_watch = &jon_snow; | |
8 | let starks = || { | |
9 | *jon_snow = 3; // error: closure requires unique access to `jon_snow` | |
10 | // but it is already borrowed | |
11 | }; | |
12 | println!("{}", nights_watch); | |
13 | } | |
14 | ``` | |
15 | ||
16 | In here, `jon_snow` is already borrowed by the `nights_watch` reference, so it | |
17 | cannot be borrowed by the `starks` closure at the same time. To fix this issue, | |
18 | you can create the closure after the borrow has ended: | |
19 | ||
20 | ``` | |
21 | fn you_know_nothing(jon_snow: &mut i32) { | |
22 | let nights_watch = &jon_snow; | |
23 | println!("{}", nights_watch); | |
24 | let starks = || { | |
25 | *jon_snow = 3; | |
26 | }; | |
27 | } | |
28 | ``` | |
29 | ||
30 | Or, if the type implements the `Clone` trait, you can clone it between | |
31 | closures: | |
32 | ||
33 | ``` | |
34 | fn you_know_nothing(jon_snow: &mut i32) { | |
35 | let mut jon_copy = jon_snow.clone(); | |
36 | let starks = || { | |
37 | *jon_snow = 3; | |
38 | }; | |
39 | println!("{}", jon_copy); | |
40 | } | |
41 | ``` |