Skip to content

Commit fd4bc91

Browse files
authored
Document some rust weird trick
Rust weird trick
1 parent 63c10ff commit fd4bc91

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

_posts/2018-01-26-rust-trick.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
```

0 commit comments

Comments
 (0)