Back to questions
JuniorTheoryCommon
What does the program print?
fn main() {
let mut s1 = String::from("hi");
let s2 = s1.clone();
s1.push('!');
println!("{s1} {s2}");
}hi! hi
- Expecting
hi! hi!:cloneon aStringallocates a separate buffer, so a later change tos1never shows up ins2. - Expecting
cloneto moves1intos2: it copies the contents into a newString, ands1keeps its own string and stays usable.
- What changes if you replace
s1.clone()with&s1? - Why does Rust make you write
.clone()instead of copying aStringon assignment?