I think there's a misunderstanding on what the map
method was made for. This methodis generally used for data transformations where the original values remain unchanged. What you are really doing here is causing a side effect, and the map
method does not help you at all here.
Just use a for
loop. It's not like you're saving keystrokes by using map and interators.
However, you mentioned you have a Vec<&Vec>
. Having this type seems unfit for your purpose. Cloning the entire vec just to add 1 element is terrible for performance.
I see 2 choices: either have it fully owned, i.e. Vec<Vec>
, or just make the inner Vec
s mutable, as in Vec<&mut Vec>
.
This is the first option, and I think this is the most idiomatic:
fn main() {
let mut vec_of_strings = vec![
vec!["a1", "b2", "c3"],
vec!["d1", "e2", "f3"],
vec!["g1", "h2", "i3"]
];
for vec in vec_of_strings.iter_mut() {
vec.push("something");
}
println!("{vec_of_strings:?}");
}
If having it in an owned form is not acceptable, then another option is to use Vec<&mut Vec>
:
fn main() {
fn main() {
let mut vec_of_strings = vec![
vec!["a1", "b2", "c3"],
vec!["d1", "e2", "f3"],
vec!["g1", "h2", "i3"]
];
//suppose somehow a function gave you this:
let vec_of_mut_strings: Vec<&mut Vec<_>> = vec_of_strings
.iter_mut()
.collect();
for vec in vec_of_mut_strings {
vec.push("something");
}
//notice that the original vec_of_strings change
println!("{vec_of_strings:?}");
}
}