<code>fn main() {
let mut s = String::from("hello");
let r1 = &s; // immutable reference
let _r2 = &s; // immutable reference
println!("{r1}");
// println!("{r2}");
let r3 = &mut s; // mutable reference, but it should throw compilation error
// as _r2 is not out of scope yet.
println!("{r3}");
}
</code>
<code>fn main() {
let mut s = String::from("hello");
let r1 = &s; // immutable reference
let _r2 = &s; // immutable reference
println!("{r1}");
// println!("{r2}");
let r3 = &mut s; // mutable reference, but it should throw compilation error
// as _r2 is not out of scope yet.
println!("{r3}");
}
</code>
fn main() {
let mut s = String::from("hello");
let r1 = &s; // immutable reference
let _r2 = &s; // immutable reference
println!("{r1}");
// println!("{r2}");
let r3 = &mut s; // mutable reference, but it should throw compilation error
// as _r2 is not out of scope yet.
println!("{r3}");
}
Expected it to not work as documentation says:
We also cannot have a mutable reference while we have an immutable one to the same value.
Play ground link