Fix a String that is moved into a function on every pass of a loop
The program should shout the same word three times and then print the word and the total number of bytes shouted. It does not compile: error[E0382]: use of moved value: `word` .
Constraints:
wordis created once, before the loop, and is still usable after it.- Compare three fixes — borrowing, cloning and handing ownership back — and keep the one that makes no extra copy of
word.
fn shout(s: String) -> usize {
println!("{}!", s.to_uppercase());
s.len()
}
fn main() {
let word = String::from("hey");
let mut total = 0;
for _ in 0..3 {
total += shout(word);
}
println!("{total}");
}Find and fix the bug.
The first call moves word into shout, so the next pass uses a moved value (E0382). Borrowing fixes it: take &str and call shout(&word). A clone allocates on every pass, and handing the String back works but clutters every call.
- Reaching for
.clone()by reflex: it allocates a new buffer on every pass when a borrow is enough - Believing
mutlets a moved value be used again: a movedmutbinding must be given a new value first - Handing the argument back in a tuple when the function only needs to read it
- Why is
&stra better parameter type than&Stringforshout? - When is moving the
Stringinto the function the right design after all?
shout takes a String, so it takes ownership of its argument. The first pass moves word into the parameter, the string is dropped at the end of shout, and on the second pass there is nothing left to pass. The compiler says so with the note value moved here, in previous iteration of loop.
The function only reads the string, so it should borrow it. A &str parameter accepts both a &String (through deref coercion) and string literals:
fn shout(s: &str) -> usize {
println!("{}!", s.to_uppercase());
s.len()
}
fn main() {
let word = String::from("hey");
let mut total = 0;
for _ in 0..3 {
total += shout(&word);
}
println!("{word}: {total}");
}The program prints HEY! three times and then hey: 9.
The two other fixes compile too, but they are worse:
shout(word.clone())keeps the signature but allocates a new buffer on every pass — the cost grows with the string's length and the number of passes.fn shout(s: String) -> (String, usize)hands ownership back, and the loop has to writelet (w, n) = shout(word); word = w;withlet mut word— noise in every call for what a reference gives for free.