0

I just started on Rust couple days ago and work through concept of ownership now.

So ok - you can't have more than one mutable reference - I dig that - so this fails:

let mut s4= String::from("ZOOT");
let s5 = &mut s4;
let s6 = &mut s4; //error here - second mutable borrow occurs here
s5.push_str(" suit"); //added this line to force error on s6

but why is this allowed???

let mut s4= String::from("ZOOT");
let s5 = &mut s4;
s5.push_str(" suit");
let s6 = &mut s4; //but WHY NOT here?

and yes println!("s6 = {} ", s6); prints ZOOT suit.

PS. I do understand that after the line let s6 = &mut s4; the s5 is no longer accessible - if you try then suddenly compiler wakes up and throws error on s6 declaration. But should it throw fit - on the second reference to s4 with or without s5 being used to modify content of s4?

Tom N
  • 51
  • 9
  • *you can't have more than one mutable reference - I dig that - so this fails:* [no it doesn't](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=dba9f912897b2aa4d7503405978d9360). – trent Feb 06 '21 at 03:58
  • Actually you are right - it fails only if I try to use reference to `s5`. Lemme upgrade the question. – Tom N Feb 06 '21 at 04:10
  • Very complete and interesting answer to my borderline trivial observation. Thank you very much - great read! – Tom N Feb 06 '21 at 07:12

0 Answers0