rustiterator

Iterator's predicate returns Result<bool, E>, how do I stop iteration and return the error


type E = String;

fn helper() -> Result<char, E> {
    let pred = |x| -> Result<bool, E> {
        if x % 3 {
            Ok(x % 2)
        } else {
            Err("error".to_string())
        }
    };
    let it = "abcde".chars().filter(pred);
    return it.next()
}

How do you solve this? Capture a mutable reference to an Option<E>?

Here's the solution to a similar problem but for map How do I stop iteration and return an error when Iterator::map returns a Result::Err?


Solution

  • You can use filter_map():

    let mut it = "abcde".chars().filter_map(|item| match pred(item) {
        Ok(should_return) => should_return.then_some(Ok(item)),
        Err(err) => Some(Err(err)),
    });
    return it.next();
    

    Or find_map() if all you want is next():

    "abcde".chars().find_map(|item| match pred(item) {
        Ok(should_return) => should_return.then_some(Ok(item)),
        Err(err) => Some(Err(err)),
    })