]> git.proxmox.com Git - rustc.git/blame - src/librustc_error_codes/error_codes/E0389.md
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_error_codes / error_codes / E0389.md
CommitLineData
60c5eb7d
XL
1#### Note: this error code is no longer emitted by the compiler.
2
3An attempt was made to mutate data using a non-mutable reference. This
4commonly occurs when attempting to assign to a non-mutable reference of a
5mutable reference (`&(&mut T)`).
6
7Erroneous code example:
8
9```compile_fail
10struct FancyNum {
11 num: u8,
12}
13
14fn 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
22Here, `&mut fancy` is mutable, but `&(&mut fancy)` is not. Creating an
23immutable reference to a value borrows it immutably. There can be multiple
24references of type `&(&mut T)` that point to the same value, so they must be
25immutable to prevent multiple mutable references to the same value.
26
27To fix this, either remove the outer reference:
28
29```
30struct FancyNum {
31 num: u8,
32}
33
34fn 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
46Or make the outer reference mutable:
47
48```
49struct FancyNum {
50 num: u8
51}
52
53fn 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```