I’m wondering why the below code does not remove all the empty strings:
fn set_name_list(&mut self, mut name_list: Vec<String>) {
// name_list is [" "]
name_list
.iter()
.map(|o| trim_all_spaces(o))
.collect::<Vec<String>>()
.retain(|o| !o.is_empty());
// name_list is [" "] here
}
but this works instead:
fn set_name_list(&mut self, mut name_list: Vec<String>) {
// name_list is [" "]
name_list = name_list
.iter()
.map(|o| trim_all_spaces(o))
.collect::<Vec<String>>();
name_list.retain(|o| !o.is_empty());
// name_list is correctly [] here
}
Why does .retain() not work chained with .iter()?
>Solution :
You can’t in fact call retain() on an iterator, because it’s not defined for iterators, but instead for the collections directly as you can see when you search for it.
What your first snippet does is instead collect into a new and temporary vector, and call retain on that, for obvious reasons this cannot remove any elements from the original.
Your second version works because you overwrite the original vector with the one you newly collect. Since you’ve stored it you can of course call retain on it and it works.