Iterator Option<T> to iterator T

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

#2

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

#3

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

0 Likes

#4

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

0 Likes

#5

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

#6

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

#7

filter_map is what I want.

Thanks!

0 Likes

#8

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

3 Likes

#9

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