HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
converthowvecresult

Problem

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

Example:

fn vec_of_result_to_result_of_vec(v: Vec>) -> Result, E>
where
    T: std::fmt::Debug,
    E: std::fmt::Debug,
{
    let mut new: Vec = 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.

Solution

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

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

Code Snippets

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

Context

Stack Overflow Q#63798662, score: 83

Revisions (0)

No revisions yet.