The missing pattern matcher

I came across a place where I’d really like to collapse:

for maybe_item in option_vec {
    if let Some(item) = maybe_item {
        // etc
    }
}

to:

for Some(item) in option_vec {
    // etc
}

It’s a minor thing. But so is if let, and that improves ergonomics.

Let us bikeshed.

filter_map to the rescue!

for really_item in option_vec.iter().filter_map(|x| x) {
    // etc
}

It will ignore anything that returns a None value, effectively including the if let for you.

6 Likes

The problem is that it’s unclear if you want it to skip Nones, or stop on the first None.

So the adapter is probably the right choice. (And you can do .flatten() if you want.)

1 Like

Itertools::while_some() is nice for that, or you can write:

while let Some(Some(item)) = iter.next() {
    // ...
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.