]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0506.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0506.md
1 An attempt was made to assign to a borrowed value.
2
3 Erroneous code example:
4
5 ```compile_fail,E0506
6 struct FancyNum {
7     num: u8,
8 }
9
10 let mut fancy_num = FancyNum { num: 5 };
11 let fancy_ref = &fancy_num;
12 fancy_num = FancyNum { num: 6 };
13 // error: cannot assign to `fancy_num` because it is borrowed
14
15 println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
16 ```
17
18 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
19 be assigned to a new value as it would invalidate the reference.
20
21 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
22
23 ```
24 struct FancyNum {
25     num: u8,
26 }
27
28 let mut fancy_num = FancyNum { num: 5 };
29 let moved_num = fancy_num;
30 fancy_num = FancyNum { num: 6 };
31
32 println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
33 ```
34
35 If the value has to be borrowed, try limiting the lifetime of the borrow using
36 a scoped block:
37
38 ```
39 struct FancyNum {
40     num: u8,
41 }
42
43 let mut fancy_num = FancyNum { num: 5 };
44
45 {
46     let fancy_ref = &fancy_num;
47     println!("Ref: {}", fancy_ref.num);
48 }
49
50 // Works because `fancy_ref` is no longer in scope
51 fancy_num = FancyNum { num: 6 };
52 println!("Num: {}", fancy_num.num);
53 ```
54
55 Or by moving the reference into a function:
56
57 ```
58 struct FancyNum {
59     num: u8,
60 }
61
62 fn print_fancy_ref(fancy_ref: &FancyNum){
63     println!("Ref: {}", fancy_ref.num);
64 }
65
66 let mut fancy_num = FancyNum { num: 5 };
67
68 print_fancy_ref(&fancy_num);
69
70 // Works because function borrow has ended
71 fancy_num = FancyNum { num: 6 };
72 println!("Num: {}", fancy_num.num);
73 ```