Match guards in Rust - Time & Space Complexity
We want to see how using match guards affects the time it takes for a program to run.
Specifically, how the number of checks grows as the input gets bigger.
Analyze the time complexity of the following code snippet.
fn count_even_greater_than_five(numbers: &[i32]) -> usize {
let mut count = 0;
for &num in numbers {
match num {
n if n % 2 == 0 && n > 5 => count += 1,
_ => (),
}
}
count
}
This code counts how many numbers in a list are even and greater than five using a match with a guard.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list once.
- How many times: Exactly once for each number in the input list.
Each number is checked once with the match guard condition.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the input size.
Time Complexity: O(n)
This means the time to run grows in a straight line as the list gets bigger.
[X] Wrong: "Match guards make the code slower by adding extra loops or checks for each condition."
[OK] Correct: The match guard only adds a simple condition check inside the existing loop, so it does not add extra loops or multiply the work.
Understanding how match guards affect performance helps you write clear and efficient Rust code, a skill that shows you think about both correctness and speed.
"What if we added a nested loop inside the match guard to check something else? How would the time complexity change?"