Filter vs FilterMap: why ref in former not latter

Here are the constraints on the functions passed to Iterator::{filter, filter_map}

P: FnMut(&Self::Item) -> bool      // filter
F: FnMut( Self::Item) -> Option<B> // filter_map

Why does the former take a ref to Item while the latter takes Item by value?

filter doesn't need to take ownership of items, it just needs to take a predicate. If filter took its item by value, you couldn't compose it with any other iterator method, because all items would be dropped (since it has no way to return an owned argument).

filter_map takes argument by value for the same reason map does: you want to transform your items in some way and pass them on. It is used to merge .filter(..).map(..) chain into a single call. Even if you don't want to modify the item itself, you can just easily pass it forward in the return value.

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.