0
0
Rustprogramming~5 mins

Result enum in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Result enum
O(n)
Understanding Time Complexity

When using Rust's Result enum, it's important to know how the time cost changes as your program runs.

We want to see how the time to handle Result values grows with input size.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fn process_results(results: &[Result]) -> i32 {
    let mut sum = 0;
    for res in results {
        match res {
            Ok(val) => sum += val,
            Err(_) => continue,
        }
    }
    sum
}
    

This code adds up all the Ok values in a list of Result items, skipping errors.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the results slice.
  • How many times: Once for every item in the input list.
How Execution Grows With Input

As the list gets longer, the time to process grows directly with the number of items.

Input Size (n)Approx. Operations
10About 10 checks and sums
100About 100 checks and sums
1000About 1000 checks and sums

Pattern observation: The work grows evenly as the input grows; doubling the input doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items to check.

Common Mistake

[X] Wrong: "Matching on each Result is slow and adds extra loops."

[OK] Correct: Matching is done inside the single loop and does not add extra passes; it's just a quick check per item.

Interview Connect

Understanding how simple loops and pattern matching affect time helps you explain your code clearly and shows you know how to reason about performance.

Self-Check

"What if we changed the input from a slice to a nested list of Result values? How would the time complexity change?"