How do you handle errors inside a Rust filter()?

Viewed 859

I'd like to use a filter function that may return an Err result, and bubble it up to the containing function:

mycoll.into_iter()
  .filter(|el| {
    if el == "bad" {
      Err(MyError)
    } else {
      Ok(el < "foo")
    }
  })

I found a good explanation on how to handle this type of case when it comes to map() (using .collect::<Result<...>>()): How do I stop iteration and return an error when Iterator::map returns a Result::Err? but I can't get a similar solution to work for filter().

What's the idiomatic solution here?

1 Answers

I'd probably suggest using filter_map. Your example would look like:

mycoll.into_iter()
  .filter_map(|el| {
    if el == "bad" {
      Some(Err(MyError))
    } else if el < "foo" {
      Some(Ok(el))
    } else {
      None
    }
  })
Related