Consider:
fn main() {
let mut x: i32 = 5;
let y = &mut x;
let z: &i32 = y;
println!("{}", *z);
//*y = 5;
println!("{}", *y);
println!("{}", *z);
}
Without commenting out line 6 the code compiles.
It seems to me that both the reference y
and z
are in scope from line 5 to 7.
It sure only reads from y
, but I've always been told that mutable and immutable reference can not exist at the same time. In fact, it results in a compile error if I replace line 4 with let z: &i32 = &x
.
What is going on here?