1

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?

Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81
  • 2
    https://manishearth.github.io/blog/2015/05/17/the-problem-with-shared-mutability/ – Ry- Feb 04 '21 at 05:39
  • 2
    From the [Rust Reference](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#the-rules-of-references): *"At any given time, you can have either one mutable reference or any number of immutable references."* - the rule is there to prevent data races. It may seem silly in this trivial example, but the rules apply to larger, more complicated scenarios where this pattern could cause an issues. – kmdreko Feb 04 '21 at 05:49
  • 1
    I've never heard of "freeze" and "unfreeze" terms used for this situation - the normal term is "borrow". A borrowed value cannot be used by the original owner as long as it is borrowed, so in a freeze analogy the "unfreeze" would take place once the borrowed reference goes out of scope. – user4815162342 Feb 04 '21 at 08:31
  • Note the linked question has 3 answers - if the first one doesn't make it click, keep reading. Also see [How do intertwined scopes create a “data race”?](/q/61851916/3650362) which was marked as a duplicate of the same one, but also has its own answer – trent Feb 04 '21 at 20:43

0 Answers0