Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn main() {
let s = String::from("hi");
let r = &mut s;
r.push('!');
println!("{s}");
}It does not compile
- Expecting
hi!: a&mutcannot be taken from a binding declared withoutmut, so the build stops with E0596 and the compiler asks forlet mut s. - Expecting a copy of
sto be changed: a&mutpoints tositself, and the compiler refuses it becauselet spromised the value would not change.
- What is the difference between
let mut r = &s;andlet r = &mut s;? - Which single change makes this program compile and print
hi!?