Unzip with error handling

Hello,

In some code, I like to unzip from an iterator of Result of tuple.
But it's seem than unzip don't handle it, unlike collect.

I want to convert an

Iterator<Item = Result<(A,B), _>

into a

Result<(Vec<A>, Vec<B>), _>

Example :

fn main() {
    let vec = vec![Ok(('a',3)), Ok(('b',6)), Ok(('i',1)), Err("bad".into())]
    let res: Result<(Vec<_>, Vec<_>),_> = vec.iter().unzip();
    let (_chars, _num) = res.unwrap();
}

Do you think it would be possible to update unzip in sush a way than it can handle Result like collect, or to implement a try_unzip ?
Or do you know an alternative ?

Thank you

This works on nightly, due to this implementation I believe, which will stabilize in Rust 1.79 (June 13).

Nice, thank you.

Here's try_unzip on stable:

pub fn try_unzip<I, C, T, E>(iter: I) -> Result<C, E>
where
    I: IntoIterator<Item = Result<T, E>>,
    C: Extend<T> + Default,
{
    iter.into_iter().try_fold(C::default(), |mut c, r| {
        c.extend([r?]);
        Ok(c)
    })
}

Rust Playground

3 Likes

Thank's too.
This is also an interesting solution.

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.