How to partition vector of results in Rust?

Viewed 1335

Basically, I'm looking for the partitionEithers equivalent in Rust, i.e. to convert Vec<Result<A, B>> into Result<Vec<A>, Vec<B>>.

I know I can transform a Vec<Result<A, B>> into Result<Vec<A>, B> by using collect::<Result<Vec<A>, B>>, but when I try collect::<Result<Vec<A>, Vec<B>>>, I'll get an error saying such implementation is missing.

Also I know this can be done using mutations, but I'm wondering if there are any immutable alternatives that I can look into?

1 Answers

You can partition by using the partition() method, on your particular case, use partition_map() from itertools:

use itertools::{Either, Itertools};
fn main() {
    let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];

    let (successes, failures): (Vec<_>, Vec<_>) =
        successes_and_failures
            .into_iter()
            .partition_map(|r| match r {
                Ok(v) => Either::Left(v),
                Err(v) => Either::Right(v),
            });

    assert_eq!(successes, [1, 2]);
    assert_eq!(failures, [false, true]);
}
Related