Can mutable and immutable reference exist at the same time?

Viewed 100

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?

1 Answers

Immutable references do not expect the underlying value to change and this is problematic if we do have a mutable reference. You can however have multiple immutable references because underlying data is not gonna change.

  • Scope of reference starts when it is first introduced and ends when it is used for the last time. That means we can add a third mutable reference underneath the println statement
    fn main() {
        let mut x: i32 = 5;
        // scope of y starts here
        // we can have multiple immutable references so I moved "mut"
        let y = &x;
        // scope of z starts here
        let z: &i32 = y;
        // scope of z ends here
        println!("{}", *z);
        //*y = 5;
        // scope of y ends here
        println!("{}", *y);
    
        // this should work
        let a = &mut x;
    }
Related