Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
fn main() {
let mut s = String::from("hi");
let r1 = &s;
println!("{r1}");
let r2 = &mut s;
r2.push('!');
println!("{s}");
}hi hi!
- Expecting a compile error: a borrow lasts until the reference's last use, not to the end of the block, so
r1is done beforer2is created. - Expecting the borrow rules to be checked while the program runs: the compiler checks them, and here the shared and the mutable borrow never overlap.
- What happens if
r1is printed once more afterr2.push('!')? - Why may the last line read
swhile the variabler2is still in scope?