]>
Commit | Line | Data |
---|---|---|
60c5eb7d XL |
1 | #### Note: this error code is no longer emitted by the compiler. |
2 | ||
3 | An attempt was made to mutate data using a non-mutable reference. This | |
4 | commonly occurs when attempting to assign to a non-mutable reference of a | |
5 | mutable reference (`&(&mut T)`). | |
6 | ||
7 | Erroneous code example: | |
8 | ||
9 | ```compile_fail | |
10 | struct FancyNum { | |
11 | num: u8, | |
12 | } | |
13 | ||
14 | fn main() { | |
15 | let mut fancy = FancyNum{ num: 5 }; | |
16 | let fancy_ref = &(&mut fancy); | |
17 | fancy_ref.num = 6; // error: cannot assign to data in a `&` reference | |
18 | println!("{}", fancy_ref.num); | |
19 | } | |
20 | ``` | |
21 | ||
22 | Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an | |
23 | immutable reference to a value borrows it immutably. There can be multiple | |
24 | references of type `&(&mut T)` that point to the same value, so they must be | |
25 | immutable to prevent multiple mutable references to the same value. | |
26 | ||
27 | To fix this, either remove the outer reference: | |
28 | ||
29 | ``` | |
30 | struct FancyNum { | |
31 | num: u8, | |
32 | } | |
33 | ||
34 | fn main() { | |
35 | let mut fancy = FancyNum{ num: 5 }; | |
36 | ||
37 | let fancy_ref = &mut fancy; | |
38 | // `fancy_ref` is now &mut FancyNum, rather than &(&mut FancyNum) | |
39 | ||
40 | fancy_ref.num = 6; // No error! | |
41 | ||
42 | println!("{}", fancy_ref.num); | |
43 | } | |
44 | ``` | |
45 | ||
46 | Or make the outer reference mutable: | |
47 | ||
48 | ``` | |
49 | struct FancyNum { | |
50 | num: u8 | |
51 | } | |
52 | ||
53 | fn main() { | |
54 | let mut fancy = FancyNum{ num: 5 }; | |
55 | ||
56 | let fancy_ref = &mut (&mut fancy); | |
57 | // `fancy_ref` is now &mut(&mut FancyNum), rather than &(&mut FancyNum) | |
58 | ||
59 | fancy_ref.num = 6; // No error! | |
60 | ||
61 | println!("{}", fancy_ref.num); | |
62 | } | |
63 | ``` |