Course contentsShow
← Rust
Lesson 851 of 1,9107. Error Handling PatternsFree lesson

Collecting Results into Collections

Transform a list of Results into a Result of a list using iterator collection.

In this lesson, you will learn how to transform an iterator of Result values into a single Result containing a collection of successful values.

The Problem: Handling Many Results

Imagine you are processing a list of strings and attempting to parse each one into an integer. Using map, you end up with an iterator of Result<i32, ParseIntError>. If even one of these operations fails, you usually want to know about it immediately rather than manually iterating through and checking each individual item.

Rust provides a powerful, idiomatic way to handle this using the .collect() method.

The Solution: Using collect()

When you call .collect() on an iterator of Result<T, E>, Rust’s standard library triggers a special behavior: it "short-circuits." If every item is an Ok(T), it will successfully gather them into a container like a Vec<T>. However, if it encounters an Err(E), it stops immediately and returns that first error it found.

Here is what that looks like in practice:

fn main() {
    let inputs = vec!["1", "2", "3"];
    
    // Attempt to parse all strings into integers
    let results: Result<Vec<i32>, _> = inputs
        .into_iter()
        .map(|s| s.parse::<i32>())
        .collect();

    match results {
        Ok(numbers) => println!("All parsed: {:?}", numbers),
        Err(e) => println!("Found an error: {}", e),
    }
}

Why This Works

The compiler is smart enough to look at the type annotation on the variable results. Because you declared it as Result<Vec<i32>, E>, the collect() method knows it needs to return a Result. It iterates through the elements, effectively performing a "logical AND" across all results.

This pattern is highly efficient because it eliminates the need for manual loops, match statements, or mutable vectors that you would otherwise have to manage yourself to push successful results into. It turns a list of potentially failing operations into a clean, atomic success or a single failure point.

Key Takeaway: Calling .collect() on an iterator of Result<T, E> will automatically transform the sequence into a Result<Collection<T>, E>, short-circuiting on the first error encountered.