3

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?

brundolf
  • 1,170
  • 1
  • 9
  • 18

1 Answers1

6

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
    }
  })
Daniel Wagner-Hall
  • 2,446
  • 1
  • 20
  • 18