You can collect directly to Result-wrapped collections, which will halt on Err:
fn main() {
let v = vec![1,2,4,5,6];
let result: Result<Vec<i32>, i32> = v.into_iter().map(|e| {
if e < 4 {
Ok(e)
} else {
Err(-1) // or whatever error type
}
}).collect();
println!("{:?}", result);
}
Thanks, but I'm confused. How can evaluating one iteration through a closure, which is supposed to return one element in the vector, return a full result of the whole mapping?
Given an iterator of Result<A, E> items, each Ok(A) is forwarded to the collection's FromIterator<A> for V, and at the end it will return that Ok(V). But if the iterator produces any Err(E), it will stop right away and return that error directly.