• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


08 Jan, 2025

Updated at 20 Jan, 2025

Why does this not pass the borrow checker?

The following code does not pass the borrow checker:

fn main() {
    let mut value: f64 = 0.0;

    let r = &mut value; // Mutable borrow

    let immut_ref = &value; // Immutable borrow
    println!("{}", immut_ref); // Use immutable reference

    *r += 1.0; // Error: cannot use `r` while `immut_ref` is active
}

In this code, an immutable reference to value is acquired and used after acquiring an immutable reference. Following that, the mutable reference is incremented.

I am of the opinion that this code is completely safe. The value that immut_ref sees is consistent, and immut_ref is not used after the increment of r.

Why is it not possible to take an immutable reference to a value on which a mutable reference exists, as long as the immutable reference is not used following any subsequent usage of the mutable reference?

Are there any examples analogous to this code which would result in memory corruption? What exactly is the borrow checker trying to prevent here?

Any input appreciated.

3 posts - 2 participants

Read full topic