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.