In a single mutable reference, there is a concept of freezing the values:
fn main() {
let mut x = 5;
let y = &mut x; // freeze
*y *= 2; // unfreeze
println!("x == {}", x);
}
This program works because it changes the value of x
through the address directly.
However, this program fails:
fn main() {
let mut x = 5;
let y = &mut x; // freeze
x *= 2;
*y *= 2; // unfreeze
println!("x == {}", x);
}
This program fails because x is mutably borrowed. I understand what is happening here but unable to understand the reasoning behind it. y
has the reference to x
and it can change the value assigned to x
but x itself can't change the value just because that value's address is stored in another variable. Why is that? y
can point to an address 1001
that had value 5 stored initially and now 10. Is there a deeper level of logic involved in this other than Rust prioritizes immutability?