Match expression deep dive in Rust - Time & Space Complexity
We want to understand how the time it takes to run a match expression changes as the number of patterns grows.
How does adding more match arms affect the work the program does?
Analyze the time complexity of the following Rust match expression.
fn describe_number(n: i32) -> &'static str {
match n {
1 => "one",
2 => "two",
3 => "three",
4 => "four",
_ => "other",
}
}
This code matches a number to a string description using several patterns.
Look for repeated checks or comparisons inside the match.
- Primary operation: Comparing the input value against each pattern in order.
- How many times: Up to the number of match arms until a match is found.
As the number of match arms increases, the program may check more patterns before finding a match.
| Input Size (number of arms) | Approx. Comparisons |
|---|---|
| 3 | Up to 3 comparisons |
| 10 | Up to 10 comparisons |
| 100 | Up to 100 comparisons |
Pattern observation: The number of comparisons grows roughly in a straight line with the number of arms.
Time Complexity: O(n)
This means the time to find a match grows linearly with the number of patterns.
[X] Wrong: "Match expressions always run in constant time no matter how many arms there are."
[OK] Correct: The program may need to check each arm one by one until it finds a match, so more arms usually mean more work.
Understanding how match expressions scale helps you explain how your code behaves with more cases, showing you think about efficiency clearly.
"What if the match arms were arranged to check the most common cases first? How would that affect the time complexity in practice?"
Practice
match expression do in Rust?Solution
Step 1: Understand the purpose of
Thematchmatchexpression is used to compare a value against several patterns.Step 2: Identify what happens on a match
When a pattern matches, the corresponding code block runs, makingmatcha clear way to handle multiple cases.Final Answer:
It compares a value against multiple patterns and executes matching code. -> Option DQuick Check:
Match expression = pattern matching [OK]
- Thinking match creates variables
- Confusing match with loops
- Assuming match defines functions
match expression in Rust?Solution
Step 1: Recall Rust match syntax
Rust uses curly braces with patterns followed by => and the code to run.Step 2: Check each option
match value { 1 => println!("One"), _ => println!("Other") } uses correct syntax with => and a default case using _; others use invalid symbols like : or -> or else.Final Answer:
match value { 1 => println!("One"), _ => println!("Other") } -> Option BQuick Check:
Correct match syntax uses => and _ for default [OK]
- Using : or -> instead of =>
- Omitting commas between arms
- Using else instead of _ for default
let x = Some(5);
match x {
Some(n) if n > 3 => println!("Greater than 3: {}", n),
Some(n) => println!("Less or equal to 3: {}", n),
None => println!("No value"),
}Solution
Step 1: Analyze the match arms and value
The value is Some(5). The first arm matches Some(n) with a guard n > 3.Step 2: Check the guard condition
Since 5 > 3 is true, the first arm runs and prints "Greater than 3: 5".Final Answer:
Greater than 3: 5 -> Option AQuick Check:
Guard true triggers first arm output [OK]
- Ignoring the if guard condition
- Choosing second arm without checking guard
- Thinking None matches Some value
match expression:
let num = 2;
match num {
1 => println!("One"),
2 => println!("Two")
3 => println!("Three"),
_ => println!("Other"),
}Solution
Step 1: Check syntax of each match arm
Each arm must end with a comma except possibly the last. The second arm lacks a comma after println!("Two").Step 2: Validate other parts
Using _ is valid for default, braces are correct, and matching integers is allowed.Final Answer:
Missing comma after the second arm (2 => ...). -> Option CQuick Check:
Commas separate match arms [OK]
- Forgetting commas between arms
- Misunderstanding _ as invalid
- Confusing braces with parentheses
Option<i32> values, how can you use a match expression inside a loop to print only the positive numbers, ignoring None and non-positive values?
Choose the correct code snippet.Solution
Step 1: Understand the requirement
We want to print only positive numbers inside Some, ignoring None and non-positive.Step 2: Analyze each option
for val in list { match val { Some(n) if n > 0 => println!("Positive: {}", n), _ => (), } } matches Some(n) with guard n > 0 and prints; others ignore with _ => (). for val in list { match val { Some(n) => println!("Positive: {}", n), None => println!("No value"), } } prints all Some values regardless of positivity. for val in list { if let Some(n) = val { if n > 0 { println!("Positive: {}", n); } } } uses if let but is not a match expression. for val in list { match val { Some(n) if n <= 0 => println!("Positive: {}", n), _ => (), } } prints non-positive numbers, opposite of requirement.Final Answer:
for val in list { match val { Some(n) if n > 0 => println!("Positive: {}", n), _ => (), } } -> Option AQuick Check:
Match with guard filters positive Some values [OK]
- Printing all Some values without checking positivity
- Using if let instead of match when asked
- Reversing guard condition
Ready to prove it?
Pass the test and this pattern moves unknown
