Idiomatic way to filter out Nones

I read somewhere that an Option is an iterator over either one or zero values, depending on whether it's a None or a Some. So it occurred to me to use flat_map() to filter out Nones.

for (line_num, line) in reader
    .lines()
    .flat_map(|lineopt| lineopt)
    .enumerate()
{
    if line.contains(&args.pattern) {
        println!("{}: {}", line_num, line);
    }
}

It works but seems kind of weird. Is the done thing, or is there a better way?

1 Like

You should be able to replace .flat_map(|lineopt| lineopt) with just .flatten()

5 Likes

Oh, nice! Thanks.

Semantically, this is also the same as .filter_map(|lineopt| lineopt) or filter_map(std::convert::identity), which can probably show the intent more clearly.

5 Likes

Ahh, makes sense, thanks!

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.