Fix code that reads a String after s1 + "-" + &s2 (E0382)
The program should join two words with a hyphen and then print the result together with both original words. It does not compile: the compiler reports error[E0382]: borrow of moved value: `s1` . Explain what + does with each operand, and fix the program.
Requirements:
- The program prints
tic-tac tic tac:s1ands2both stay usable after the join. - Keep
s1ands2asStrings; nounsafe. - Say which fix you would pick if
s1were not needed after the join.
fn main() {
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = s1 + "-" + &s2;
println!("{s3} {s1} {s2}");
}Find and fix the bug.
+ calls add(self, &str): it takes the left String by value, appends the right &str to that same buffer and returns it, so s1 is moved. Build s3 with format!("{s1}-{s2}"), which only borrows, or start from s1.clone().
- Thinking
+borrows both strings and allocates a new one, as in most languages - Writing
&s1 + "-", which does not compile because&Stringhas no+ - Cloning by reflex where
format!builds the result without moving anything
- Why is the right operand of
+a&strand not aString? - Why is
s1 + &s2cheaper thanformat!whens1is no longer needed?
The + operator on strings is the method add(self, other: &str) -> String. The left string goes in by value: the bytes of the right one are appended to its buffer, and the same buffer comes back as the result. So after let s3 = s1 + "-" + &s2; the variable s1 owns nothing, while s2 is intact — only a reference to it was passed. The right side is always a &str: &s2 has type &String and turns into a &str automatically.
fn main() {
let s1 = String::from("tic");
let s2 = String::from("tac");
// format! only borrows its arguments and returns a new string
let s3 = format!("{s1}-{s2}");
println!("{s3} {s1} {s2}"); // tic-tac tic tac
// a copy goes into +, and s1 keeps its owner
let s4 = s1.clone() + "-" + &s2;
println!("{s4} {s1}"); // tic-tac tic
// if s1 is no longer needed, its buffer can be handed over without copying
let mut s5 = s1;
s5.push('-');
s5.push_str(&s2);
println!("{s5}"); // tic-tac
}format! reads best when the original strings are still needed: it moves nothing. s1.clone() + … works too, but copies the bytes of s1 only so that + can take them. If s1 is not needed after the join, the original code is nearly right: + or push_str appends into its buffer without a new allocation, which is cheaper than format!. Writing &s1 + "-" does not help — error[E0369]: cannot add `&str` to `&String` : a reference has no buffer of its own to append to.