]> git.lizzy.rs Git - rust.git/blob - src/librustc_error_codes/error_codes/E0506.md
Auto merge of #66396 - smmalis37:pythontest, r=alexcrichton
[rust.git] / src / librustc_error_codes / error_codes / E0506.md
1 This error occurs when an attempt is 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 fn main() {
11     let mut fancy_num = FancyNum { num: 5 };
12     let fancy_ref = &fancy_num;
13     fancy_num = FancyNum { num: 6 };
14     // error: cannot assign to `fancy_num` because it is borrowed
15
16     println!("Num: {}, Ref: {}", fancy_num.num, fancy_ref.num);
17 }
18 ```
19
20 Because `fancy_ref` still holds a reference to `fancy_num`, `fancy_num` can't
21 be assigned to a new value as it would invalidate the reference.
22
23 Alternatively, we can move out of `fancy_num` into a second `fancy_num`:
24
25 ```
26 struct FancyNum {
27     num: u8,
28 }
29
30 fn main() {
31     let mut fancy_num = FancyNum { num: 5 };
32     let moved_num = fancy_num;
33     fancy_num = FancyNum { num: 6 };
34
35     println!("Num: {}, Moved num: {}", fancy_num.num, moved_num.num);
36 }
37 ```
38
39 If the value has to be borrowed, try limiting the lifetime of the borrow using
40 a scoped block:
41
42 ```
43 struct FancyNum {
44     num: u8,
45 }
46
47 fn main() {
48     let mut fancy_num = FancyNum { num: 5 };
49
50     {
51         let fancy_ref = &fancy_num;
52         println!("Ref: {}", fancy_ref.num);
53     }
54
55     // Works because `fancy_ref` is no longer in scope
56     fancy_num = FancyNum { num: 6 };
57     println!("Num: {}", fancy_num.num);
58 }
59 ```
60
61 Or by moving the reference into a function:
62
63 ```
64 struct FancyNum {
65     num: u8,
66 }
67
68 fn main() {
69     let mut fancy_num = FancyNum { num: 5 };
70
71     print_fancy_ref(&fancy_num);
72
73     // Works because function borrow has ended
74     fancy_num = FancyNum { num: 6 };
75     println!("Num: {}", fancy_num.num);
76 }
77
78 fn print_fancy_ref(fancy_ref: &FancyNum){
79     println!("Ref: {}", fancy_ref.num);
80 }
81 ```