Handling errors with match in Rust - Time & Space Complexity
When we handle errors using match in Rust, we want to know how the time to run the code changes as input grows.
We ask: How much work does the program do when matching on results?
Analyze the time complexity of the following code snippet.
fn process_numbers(nums: &[i32]) {
for &num in nums {
match num.checked_mul(2) {
Some(val) => println!("Double: {}", val),
None => println!("Overflow for {}", num),
}
}
}
This code doubles each number if possible, or prints an overflow message if not.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the input slice.
- How many times: Once for every number in the input list.
Each number causes one check and one print. More numbers mean more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and prints |
| 100 | About 100 checks and prints |
| 1000 | About 1000 checks and prints |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "Matching on errors makes the code slower in a way that depends on the error type."
[OK] Correct: Matching just checks the result once per item, so it grows only with the number of items, not the error details.
Understanding how error handling affects performance helps you write clear and efficient Rust code, a skill useful in many real projects.
"What if we replaced the loop with recursion? How would the time complexity change?"