Result enum in Rust - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the
resultsslice. - How many times: Once for every item in the input list.
As the list gets longer, the time to process grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and sums |
| 100 | About 100 checks and sums |
| 1000 | About 1000 checks and sums |
Pattern observation: The work grows evenly as the input grows; doubling the input doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items to check.
[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.
Understanding how simple loops and pattern matching affect time helps you explain your code clearly and shows you know how to reason about performance.
"What if we changed the input from a slice to a nested list of Result values? How would the time complexity change?"