I was just reading about mut
and how it differs from &mut
, and when you want to use the two.
So I was going through this article.
The article has this code snippet, where two mutable references are made to the same variable:
fn main() {
let mut i:i32 = 1;
let ref_i = &mut i;
let another_ref_i = &mut i;
}
According to the article, this should fail, because two active mutable references are not allowed, so it should fail with this error:
error[E0499]: cannot borrow `i` as mutable more than once at a time
--> src/main.rs:4:29
|
3 | let ref_i = &mut i;
| - first mutable borrow occurs here
4 | let another_ref_i = &mut i;
| ^ second mutable borrow occurs here
5 | }
| - first borrow ends here
But this does not happen for me. For me it compiles fine.
I then looked in the rust handbook, for a similar example, and found this:
fn main() {
let mut x = 5;
let y = &mut x;
*y += 1;
println!("{}", x);
}
Which should fail with the same error. But does'nt.
This confuses me I thought that a mutable reference would disallow the borrowed value to be used for the rest of the code.
Can someone help me with what it happening?