Having more than two mutable references for Strings


I thought we are not allowed to have more than two mutable references to a String.

fn main()
    let mut x = String::from("Hello");

    let a = &mut x;
    let b = &mut x;

How is this allowed then my compiler is not given any errors?

Thanks to a feature called non-lexical lifetimes, a borrow no longer lasts the whole lexical scope if you don’t use it.

In the above case, neither borrow is used, so they “end” immediately, allowing other mutable borrows to happen.


Is this something new that has been added?

It came with the 2018 edition in Rust 1.31, released on Dec. 06, 2018. It will also be available in Rust 2015 soon.

1 Like

As in this coming Thursday when Rust 1.36.0 is scheduled for release.