Vec<Result<A, B>> -> Result<Vec<A>, B>?

What is the idiomatic way to do:

fn foo(input: Vec<Result<A, B>>) -> Result<Vec<A>, B>
  let mut ans = vec![];
  for x in input {
    ans.push(x?);
  }
  return ans;
}

So if all Results are Ok, we return the Ok items.
If there is any Err, we return the first Err.

You can use collect() here because Result implements FromIterator.

1 Like

Thanks! This answer sounds familiar, I think I asked the exact question before.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.