Match with enums in Rust - Time & Space Complexity
We want to understand how the time it takes to run a match statement with enums changes as we add more enum variants.
How does the number of enum cases affect the work done during matching?
Analyze the time complexity of the following code snippet.
enum Color {
Red,
Green,
Blue,
Yellow,
}
fn describe_color(color: Color) -> &'static str {
match color {
Color::Red => "Red",
Color::Green => "Green",
Color::Blue => "Blue",
Color::Yellow => "Yellow",
}
}
This code matches an enum value to return a string describing the color.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The match statement checks the enum variant.
- How many times: It checks once per call, but internally it may compare against each variant until it finds a match.
As the number of enum variants grows, the match may need to check more cases before finding the right one.
| Number of Variants (n) | Approx. Checks |
|---|---|
| 4 | Up to 4 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows roughly in a straight line with the number of variants.
Time Complexity: O(n)
This means the time to find the matching enum variant grows linearly with the number of variants.
[X] Wrong: "Matching an enum is always constant time because it's just one check."
[OK] Correct: The match may check multiple variants one by one until it finds a match, so more variants can mean more checks.
Understanding how matching enums scales helps you reason about code efficiency and choose the right data structures in real projects.
"What if we used a hash map to store enum variant data instead of match? How would the time complexity change?"
Practice
What does the match statement do when used with enums in Rust?
Solution
Step 1: Understand the purpose of
Thematchwith enumsmatchstatement compares the enum value against each variant.Step 2: Identify what happens on a match
When a variant matches, the corresponding code block runs.Final Answer:
It checks the enum variant and runs the matching code block. -> Option AQuick Check:
Match runs code by enum variant [OK]
- Thinking match converts enums to strings
- Assuming match creates or deletes variants
- Confusing match with if-else statements
Which of the following is the correct syntax to match an enum Color with variants Red, Green, and Blue?
enum Color { Red, Green, Blue }Solution
Step 1: Recall enum variant syntax in match
Enum variants must be prefixed with the enum name and double colon, likeColor::Red.Step 2: Check each option's syntax
Only match color { Color::Red => {}, Color::Green => {}, Color::Blue => {} } uses the correctColor::Variantsyntax.Final Answer:
match color { Color::Red => {}, Color::Green => {}, Color::Blue => {} } -> Option CQuick Check:
Enum variants use EnumName::Variant [OK]
- Omitting enum name prefix
- Using dot instead of double colon
- Using strings instead of variants
What will be the output of this Rust code?
enum Direction { North, South, East, West }
fn main() {
let dir = Direction::East;
let message = match dir {
Direction::North => "Going up",
Direction::South => "Going down",
Direction::East => "Going right",
Direction::West => "Going left",
};
println!("{}", message);
}Solution
Step 1: Identify the enum variant assigned
The variablediris set toDirection::East.Step 2: Match
The match arm fordirto the correct messageDirection::Eastreturns "Going right".Final Answer:
Going right -> Option AQuick Check:
Direction::East matches "Going right" [OK]
- Mixing up enum variants and their messages
- Forgetting to use EnumName::Variant in match
- Assuming default or fallback arm runs
Find the error in this Rust code snippet using match with enums:
enum Status { Success, Failure }
fn check(status: Status) {
match status {
Status::Success => println!("Success"),
// Missing Failure arm
}
}Solution
Step 1: Check completeness of match arms
The match statement coversStatus::Successbut missesStatus::Failure.Step 2: Understand Rust's exhaustiveness requirement
Rust requires all enum variants to be matched or a catch-all arm (_) to avoid compile errors.Final Answer:
Missing match arm for Status::Failure -> Option DQuick Check:
All enum variants must be matched [OK]
- Leaving out enum variants in match arms
- Assuming partial match compiles
- Confusing semicolon placement with match completeness
Given this enum with data:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}Which match arm correctly extracts the x and y values from Message::Move?
Solution
Step 1: Identify the enum variant with named fields
Moveuses named fields{ x: i32, y: i32 }.Step 2: Match syntax for named fields
UseMessage::Move { x, y }to destructure named fields directly.Final Answer:
Message::Move { x, y } => println!("x: {}, y: {}", x, y), -> Option BQuick Check:
Named fields use braces and field names [OK]
- Using tuple pattern for struct-like variant
- Mixing colon syntax incorrectly
- Omitting braces for named fields
Ready to prove it?
Pass the test and this pattern moves unknown
