]> git.proxmox.com Git - rustc.git/blame - src/librustc_error_codes/error_codes/E0500.md
New upstream version 1.42.0+dfsg0+pve1
[rustc.git] / src / librustc_error_codes / error_codes / E0500.md
CommitLineData
d9bb1a4e
FG
1A borrowed variable was used by a closure.
2
3Erroneous code example:
4
5```compile_fail,E0500
6fn 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
16In here, `jon_snow` is already borrowed by the `nights_watch` reference, so it
17cannot be borrowed by the `starks` closure at the same time. To fix this issue,
18you can create the closure after the borrow has ended:
19
20```
21fn 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
30Or, if the type implements the `Clone` trait, you can clone it between
31closures:
32
33```
34fn 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```