Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does `.retain()` not work chained with `.iter()`?

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()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading