Append to and uppercase a caller's Vec<String> through &mut
Write shout_all: it receives the caller's list of names, appends the name zed and then turns every entry, the new one included, into upper case. The caller must still own the vector and use it after the call.
Requirements:
- Keep the signature
fn shout_all(names: &mut Vec<String>); do not take the vector by value and do not return it. - Change the entries in place: no second vector, no
clone. - For the input
["ann", "bob"],mainprints["ANN", "BOB", "ZED"].
fn shout_all(names: &mut Vec<String>) {
// your code here
}
fn main() {
let mut names = vec![String::from("ann"), String::from("bob")];
shout_all(&mut names);
println!("{names:?}");
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Take names: &mut Vec<String>, call push, then loop over names.iter_mut() assigning *name = name.to_uppercase(). The caller passes &mut names; ownership never moves, so main prints the changed vector afterwards.
- Taking
Vec<String>by value and then finding that the caller's variable has been moved - Iterating with
iter()and trying to assign through a shared&String - Forgetting the
*when replacing an element through&mut String
- Why can't the loop use
for name in names.iter()to change the entries? - When would a function take
&mut [String]instead of&mut Vec<String>?
The function receives a mutable reference: it may change the vector, while main stays the owner.
fn shout_all(names: &mut Vec<String>) {
names.push(String::from("zed"));
for name in names.iter_mut() {
*name = name.to_uppercase();
}
}
fn main() {
let mut names = vec![String::from("ann"), String::from("bob")];
shout_all(&mut names);
println!("{names:?}"); // ["ANN", "BOB", "ZED"]
}push is called through the &mut with no star: the dot dereferences on its own. iter_mut() yields a &mut String for each element, and *name = … replaces the string inside the vector; without the * the assignment would try to store a String in a variable of type &mut String. With iter() the elements would arrive as &String, and nothing can be written through them. When only ASCII letters matter, name.make_ascii_uppercase() changes the bytes in place with no new allocation. main writes &mut names at the call too, so the call site shows that the function may change the vector, and after the call names still belongs to main.