Multiple simultaneous mutable reference

Hi,

I don't understand why the below code will compile:

fn main() {
    let mut s = String::from("hello, ");

    let r1 = &mut s;
    r1.push_str("world");
    let r2 = &mut s;
    r2.push_str("!");

    println!("{}", r2);
}

In the book "The Rust programming Language" it is written that you can't have multiple simultaneous mutable reference. But it seems to work here...
By adding println!("{}", r1); before and after r2, it seems to me that r1 simply goes out of scope once r2 is created. Is this the correct interpretation ?

"Goes out of scope" is not precise, because it's in scope until the end of its… well, scope (which is the block forming the body of fn main()).

However, the compiler performs control flow sensitive liveness analysis, and it infers that r1 isn't actually used in a way that it would overlap with r2, so it accepts the code.

2 Likes

Thank you for your help.

Usually you don't need multiple mutable references. But if you do, You should take a look at the reference counter page.

Reference Counters; However, Are not thread safe. So if you plan on sharing this variable between threads. You should take a look at the Asynchronous Reference Counter