How do I convert a Vec<Result<T, E>> to Result<Vec<T>, E>?

Viewed 8177

Is there any opinionated and more elegant way to convert Vec<Result<T, E>> to Result<Vec<T>, E>? I want to get Ok<Vec<T>> if all values of vector are Ok<T> and Err<E> if at least one is Err<E>.

Example:

fn vec_of_result_to_result_of_vec<T, E>(v: Vec<Result<T, E>>) -> Result<Vec<T>, E>
where
    T: std::fmt::Debug,
    E: std::fmt::Debug,
{
    let mut new: Vec<T> = Vec::new();

    for el in v.into_iter() {
        if el.is_ok() {
            new.push(el.unwrap());
        } else {
            return Err(el.unwrap_err());
        }
    }

    Ok(new)
}

I'm looking for a more declarative way to write this. This function forces me to write a where clause which will never be used and Err(el.unwrap_err()) looks useless. In other words, the code does many things just to make the compiler happy. I feel like this is such a common case that there's a better way to do it.

2 Answers

An iterator over Result<T, E> can be collect()-ed directly into a Result<Vec<T>, E>; that is, your entire function can be replaced with:

let new: Result<Vec<T>, E> = v.into_iter().collect()

You can use the FromIterator trait implementation on Result (.collect() requires FromIterator on the destination type and calls into it for the conversion from Iterator):

fn vec_of_result_to_result_of_vec<T, E>(v: Vec<Result<T, E>>) -> Result<Vec<T>, E> {
    v.into_iter().collect()
}
Related