0

I am reading about references in Rust. Below is text snippet from Programming Rust

As long as there are shared references to a value, not even its owner can modify it; the value is locked down. Nobody can modify table while show is working with it. Similarly, if there is a mutable reference to a value, it has exclusive access to the value; you can’t use the owner at all, until the mutable reference goes away. Keeping sharing and mutation fully separate turns out to be essential to memory safety

I have written below code

let mut a = vec![1, 2, 3];
    let b = &mut a;
    b.push(5);
    a.push(4);

Code is compiling with out errors. My understanding is that since variable "b" is mutable reference in scope so a.push should fail with descritpion provided in above text. Kindly correct me if I am wrong

venkysmarty
  • 11,099
  • 25
  • 101
  • 184
  • 3
    The lifetime of the mutable reference only last as far as it is used. This wasn't always the case, this more flexible behavior was introduced with ["non-lexical lifetimes"](https://stackoverflow.com/questions/50251487/what-are-non-lexical-lifetimes) in 2018. – PitaJ Feb 15 '23 at 21:27
  • Hm, however [Rust 2015](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=c28ef7f41ca2b53daa50f118cac19e2b) also compiles... – Primer Feb 16 '23 at 05:52
  • Because "As of Rust 1.36, the Rust 2015 edition also enables non-lexical lifetimes." - from [linked question](https://stackoverflow.com/a/50253558/4077912) – Primer Feb 16 '23 at 06:08

0 Answers0