Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn main() {
let mut s = String::from("hi");
let r1 = &mut s;
let r2 = &mut s;
r1.push('!');
r2.push('?');
println!("{s}");
}It does not compile
- Expecting
hi!?:r1is used afterr2is created, so two&muttosare alive at once, and the compiler stops with E0499. - Expecting the second
&mutto take over quietly: Rust never invalidates a reference behind your back; overlapping&mutborrows are a compile error.
- How would you reorder the lines so that the program compiles and prints
hi!?? - Why is a second
&mutrefused even when the program has only one thread?