Doubt on References Rules in Rust

Hi guys!

I just wanted to understand one aspect of the Rust's references Rules:
At any given moment, I can only have an unlimited number of immutable references of a variable OR a single mutable reference of a variable, correct?
In the program below, if I take the mut keyword from line 2, the program will of course complain. But, if the mut keyword on line 2 holds, why does Rust does not complain?
Thank you in advance!

fn main() {
  let mut x = 10;

  let _ref1 = &x;
  let _ref2 = &x;
  let _ref_mut = & mut x;
  *_ref_mut = 9;
  println!("{}", *_ref_mut);





   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.78s
     Running `target/debug/playground`

Because all of this code is in a single function, Rust can tell that you’re done with _ref1 and _ref2 before you construct _ref_mut. If you change the last line to:

println!("{}", *_ref1);

Then this is no longer true and your code won’t compile.

Ok, I get it now! Thank you!

I've also just found the snippet of the telling the same thing.

Historically, this did indeed not work, until we got an improved borrow checker together with the 2018 Edition which was able to reason about "Non-Lexical Lifetimes" (NLLs).


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.