0
0
Rustprogramming~5 mins

Handling errors with match in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Handling errors with match
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each number causes one check and one print. More numbers mean more work.

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

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input list gets bigger.

Common Mistake

[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.

Interview Connect

Understanding how error handling affects performance helps you write clear and efficient Rust code, a skill useful in many real projects.

Self-Check

"What if we replaced the loop with recursion? How would the time complexity change?"