File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : post
3
+ title : Weird Rust trick
4
+ ---
5
+
6
+ ### Weird Rust trick
7
+
8
+ In Rust you cannot create another reference to a value if you already have a mutable reference to it. Example:
9
+ ```
10
+ fn main() {
11
+ let mut x = 10;
12
+ let rx = &mut x;
13
+ *rx = 100;
14
+
15
+ let irx = &x;
16
+ println!("irx={}", irx);
17
+ }
18
+ ```
19
+ If you compile this code you will receive the following errors:
20
+ ```
21
+ Compiling playground v0.0.1 (file:///playground)
22
+ error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable
23
+ --> src/main.rs:6:16
24
+ |
25
+ 3 | let rx = &mut x;
26
+ | - mutable borrow occurs here
27
+ ...
28
+ 6 | let irx = &x;
29
+ | ^ immutable borrow occurs here
30
+ ...
31
+ 9 | }
32
+ | - mutable borrow ends here
33
+
34
+ error: aborting due to previous error
35
+
36
+ error: Could not compile `playground`.
37
+
38
+ To learn more, run the command again with --verbose.
39
+ ```
40
+
41
+ However you can trick the borrower checker by using a reference to a reference instead. So the code below will compile successfully in rust.
42
+ ```
43
+ fn main() {
44
+ let mut x = 10;
45
+ let rx = &mut x;
46
+ *rx = 100;
47
+
48
+ let irx = ℞
49
+ println!("irx={}", irx);
50
+ }
51
+ ```
You can’t perform that action at this time.
0 commit comments