Iterator of results to result of iterator

I need to interrupt an Iterator<Result<O, E>> if one of results is an Err. Can I do this?
I am looking for an iterator function, something like this: Iterator<Result<O, E>> -> Result<Iterator<O>, E>.

I know that I can use the function collect, but it makes new Vec (Result<Vec<O>, E>).
What if I don't need to allocate a Vec, but just iterate further?

You can't know from Iterator<Result<O, E>> that this iterator will fail without actual iteration. And the iteration in general consumes the iterator itself.


This crate might be of interest:


What if I don't need to allocate a Vec, but just iterate further?

I'm not sure but as I understand you want to handle errors but keep on iterating over valid values.

If I'm right the filter_map() adapter should suit you.

// impl Iterator<Item=Resutl<O, E>>
fallible_iterator.filter_map(|res| match res {
    Ok(value) => Some(value),
    Err(e) => {
        // Some processing
// Now impl Iterator<Item=O>
.map(|value| ...)

Like @Hyeonu said, you can't have a function like Iterator<Result<O, E>> -> Result<Iterator<O>, E> as to have a Result you need to already know if it succeeds or fails, but you can lift Iterator<Result<O, E>> into a Iterator<O> inside a closure. Use process_results from crate itertools or implement one by yourself.

Honestly this or some other alternatives should be included in the std. I have seen so many questions searching for this functionality.

1 Like

Thanks for answers! I''ll try to use process_results. This is what I need.

A short version is to use flatten(). Result implements IntoIterator so flatten will do the same thing.

1 Like

But only if you don't want to process either Ok or Err values. I thought nano would like to process the error values, e.g. counting them.

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