1

I was reading The Rust Programming Language book 2nd edition. In the Understanding Ownership chapter, page 95, it was saying that you can't have 2 mutable references.

But when I tried this:

fn main() {
    let mut s = String::from("Hi, mom!");

    let _r1 = &s;
    let _r2 = &s;

    let _r3 = &mut s;
    let _r4 = &mut s;
}

It worked and compiled with no error.

Shouldn't it give me a compile error?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Sobhy Rzk
  • 11
  • 2
  • tl;dr: Yes, kind of. The underlying borrowing rules have not changed (as evidenced by the fact you can make this code compile by adding enough `{` and `}`), but the compiler is smarter now about how it applies them. – trent Dec 23 '21 at 15:28
  • References are now treated as in-scope only up until their last use (and not the entire scope in which they exist), so as long as the first and last uses of `_r3` and of `_r4` don't intersect, you won't have a problem. – BallpointBen Dec 23 '21 at 22:23
  • The new book [uses the reference](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-references), for this reason. – Chayim Friedman Dec 23 '21 at 22:57

0 Answers0