banner
davirain

davirain

twitter
github
知乎
twitter

Convert Vec<Result<T>, E> to Result<Vec<T>, E>

To convert a Vec<Result<T, E>> to a Result<Vec, E>, you can use the try_fold() method from the Iterator trait. Here's an example implementation:

Here, we use into_iter() to convert the Vec into an iterator. We then call try_fold(), passing in an initial value of Vec::new() and a closure that takes two arguments: an accumulator (acc) and a Result (res).

fn vec_result_to_result_vec<T, E>(v: Vec<Result<T, E>>) -> Result<Vec<T>, E> {
    v.into_iter().try_fold(Vec::new(), |mut acc, res| {
        match res {
            Ok(t) => {
                acc.push(t);
                Ok(acc)
            },
            Err(e) => Err(e)
        }
    })
}

The closure pattern matches on the Result variant, pushing the Ok value onto the acc vector and returning Ok(acc), or returning Err(e) if the Result is an Err. The try_fold() method will continue to iterate over the remaining items in the iterator, passing the updated accumulator value to each subsequent call of the closure.

If any of the Results in the original Vec are Errs, try_fold() will short-circuit and return the first Err encountered. Otherwise, it will return Ok(acc) with the Vec of unwrapped T values.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.