0

I am learning Rust from The Rust Programming Language and I am having a WTF moment when code that is not supposed to compile is compiling.

Rust has a rule that you can have only 1 mutable reference to a given data in a particular scope. Which means this code isn't suppose to compile:

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

    let r1 = &mut s1;
    let r2 = &mut s1;

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

This compiles with no errors!

The expected error only happens when I uncomment the println!. Why does it let me declare multiple references? Doesn't it make more sense to stop me when I declare multiple mutable references rather than when I use them?

What is going on here? I am using Rust 1.39.0.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ng.newbie
  • 2,807
  • 3
  • 23
  • 57
  • 1
    You never use `r1` after `r2`, so the borrow of `s1` by `r1` is implicitly released. – Shepmaster Dec 17 '19 at 18:53
  • See also [Rust compiler not always throwing borrowing errors](https://stackoverflow.com/q/57189167/155423); [What changed in Rust that allows this borrow after a mutable borrow?](https://stackoverflow.com/q/57743044/155423); [Why did compiler not error on this mutable borrow when there is an immutable borrowed string slice reference still in scope?](https://stackoverflow.com/q/53954053/155423) – Shepmaster Dec 17 '19 at 18:55

0 Answers0