Iterator Option<T> to iterator T

  1. We have an iterator over Option<T>. How do we get an iterator over T ?

That depends on what you want to do with the None values. The easiest one would be iter.map(|o| o.unwrap). Other options include using filter, filter_map and take_while.

1 Like

Won't .unwrap() cause panic!() if any of the elems are None ?

I want the None to be dropped, and the Some to be unwrapped.

Sure, as I said, depends on what you want to do with None. If you want to panic, that's it :slight_smile:

(e) Ok, then look at filter_map.

4 Likes

I would use an identity filter_map(|opt| opt). In 1.33, you'll be able use std::convert::identity for the mapping function here, as its last example shows.

3 Likes

filter_map is what I want.

Thanks!

It would be even easier to just call .flatten() on the outer iterator

3 Likes

The implementation for flatten is more complicated though, having to treat each item as a full iterator, even though Option only ever produces one item or nothing. It's possible the optimizer can still do a good job breaking that down, but I'd rather give it a simpler filter_map.

This is even more true if you want to switch to rayon's ParallelIterator.

1 Like