Having more than two mutable references for Strings

https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html

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.

3 Likes

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.