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?"
Practice
Result enum in Rust represent?Solution
Step 1: Understand the purpose of
ResultResultis used to show if an operation succeeded or failed.Step 2: Identify the two variants
Okmeans success,Errmeans failure or error.Final Answer:
A value that can be either success (Ok) or failure (Err) -> Option CQuick Check:
Result= success or failure [OK]
- Thinking Result is a list or collection
- Confusing Result with loops or arrays
- Assuming Result always means success
Result with a success value of 10?Solution
Step 1: Check the correct variant for success
Success usesOk, soOk(10)is correct.Step 2: Verify the type matches
The type isResult, soOk(10)matchesi32for success.Final Answer:
let x: Result<i32, &str> = Ok(10); -> Option DQuick Check:
Success = Ok(value) [OK]
- Using Err for success value
- Mismatching types inside Ok or Err
- Trying to use Result::Ok instead of Ok directly
fn divide(a: i32, b: i32) -> Result {
if b == 0 {
Err(String::from("Divide by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10, 2) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
}Solution
Step 1: Check the divide function call
Callingdivide(10, 2)meansbis 2, not zero, so it returnsOk(10 / 2)which isOk(5).Step 2: Match on the Result
ThematchseesOk(5), so it printsResult: 5.Final Answer:
Result: 5 -> Option BQuick Check:
Ok(5) prints Result: 5 [OK]
- Assuming divide by 2 returns error
- Confusing Ok and Err branches
- Expecting compile error due to String
Result:fn get_number(flag: bool) -> Result {
if flag {
Ok(42)
} else {
Err(42)
}
}Solution
Step 1: Check the function return type
The function returnsResult<i32, String>, soOkmust holdi32andErrmust holdString.Step 2: Identify the error in
Err(42)42is an integer, butErrexpects aString. This causes a type mismatch.Final Answer:
TheErrvariant has wrong type; should be a String -> Option AQuick Check:
Err type must match declared error type [OK]
- Using wrong type inside Err
- Thinking Ok needs String
- Ignoring type mismatch errors
Result handling?let strings = vec!["10", "abc", "20", "xyz"];
// Fill in the blank:
let numbers: Vec<i32> = strings.iter()
.map(|s| s.parse::<i32>())
.__________;
println!("{:?}", numbers);Solution
Step 1: Understand
EachparsereturnsResults.parse::<i32>()returnsResult<i32, _>, so we get an iterator of Results.Step 2: Use
filter_map(Result::ok)to keep only successesfilter_map(Result::ok)extracts theOkvalues and skips errors, thencollect()gathers them into a vector.Final Answer:
filter_map(Result::ok).collect() -> Option AQuick Check:
filter_map(Result::ok) keeps only successful parses [OK]
- Using filter without extracting Ok values
- Calling unwrap on all results causing panic
- Trying to collect without filtering errors
Ready to prove it?
Pass the test and this pattern moves unknown
