0

To prevent data conflict, a variable cannot have its multiple mutable references at the same time but why we can just define unsafe references and get a passed compile, if we don't use them at all?

fn tut(){
    let mut s = String::from("hello");
    let s1 = &mut s;
    let s2 = &mut s;
    let s3 = &mut s;
}
StasVo
  • 554
  • 6
  • 6

1 Answers1

3

You don't really have three mutable references at once. From https://doc.rust-lang.org/stable/book/ch04-02-references-and-borrowing.html:

Note that a reference’s scope starts from where it is introduced and continues through the last time that reference is used.

s2 is not in the same scope as s1, because s1 is never used again after s2 is defined. Likewise, s2 is never used after s3 is defined.

This is similar to the example shown in the link above:

let mut s = String::from("hello");

let r1 = &s; // no problem
let r2 = &s; // no problem
println!("{} and {}", r1, r2);
// variables r1 and r2 will not be used after this point

let r3 = &mut s; // no problem
println!("{}", r3);

r3 is allowed because even though two immutable references were defined, neither r1 nor r2 is used again after r3 is defined, so they are no longer in scope to prevent r3 from being defined.

chepner
  • 497,756
  • 71
  • 530
  • 681