Enum variants in Rust - Time & Space Complexity
When working with enum variants in Rust, it's important to know how the program's running time changes as you use them.
We want to see how checking or matching enum variants affects the time it takes to run the code.
Analyze the time complexity of the following code snippet.
enum Color {
Red,
Green,
Blue,
}
fn is_red(color: &Color) -> bool {
match color {
Color::Red => true,
_ => false,
}
}
This code defines an enum with three variants and a function that checks if a given color is Red.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Matching the enum variant once per function call.
- How many times: Exactly once each time
is_redis called.
Checking the enum variant takes the same amount of time no matter how many variants exist or how many times you call the function.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 check |
| 10 | 10 checks |
| 1000 | 1000 checks |
Pattern observation: Each call does one check, so the total work grows directly with how many times you call the function.
Time Complexity: O(1)
This means checking an enum variant takes the same short time every time, no matter what.
[X] Wrong: "Matching enum variants gets slower if the enum has more variants."
[OK] Correct: Rust uses efficient code to check variants, so the time stays constant regardless of how many variants exist.
Understanding how enum variant checks work helps you reason about code speed and write clear, efficient Rust programs.
"What if we changed the enum to hold data inside each variant? How would the time complexity of matching change?"
Practice
enum variant in Rust?Solution
Step 1: Understand enum structure
An enum groups related named options called variants.Step 2: Define variant role
Each variant represents a possible value the enum can hold.Final Answer:
A named option inside an enum representing a possible value -> Option BQuick Check:
Enum variant = named option [OK]
- Confusing variants with functions
- Thinking variants are variables
- Mixing variants with loops
Red inside an enum Color?Solution
Step 1: Recall enum syntax
Enums use the syntaxenum Name { Variant1, Variant2 }.Step 2: Match correct syntax
enum Color { Red } correctly defines enumColorwith variantRed.Final Answer:
enum Color { Red } -> Option AQuick Check:
Enum variant syntax = enum Name { Variant } [OK]
- Using '=' instead of braces
- Defining variants inside struct
- Using let instead of enum
enum Direction {
North,
East,
South,
West,
}
fn main() {
let dir = Direction::East;
match dir {
Direction::North => println!("Going North"),
Direction::East => println!("Going East"),
Direction::South => println!("Going South"),
Direction::West => println!("Going West"),
}
}Solution
Step 1: Identify enum variant assigned
The variablediris set toDirection::East.Step 2: Match statement output
The match arm forDirection::Eastprints "Going East".Final Answer:
Going East -> Option CQuick Check:
Match on Direction::East prints "Going East" [OK]
- Confusing variant names
- Ignoring match arms
- Assuming default output
enum Status {
Active,
Inactive,
}
fn main() {
let s = Status::active;
}Solution
Step 1: Check variant usage
The code usesStatus::activebut enum definesActivewith uppercase A.Step 2: Understand Rust case sensitivity
Rust enum variants are case-sensitive;activeis undefined.Final Answer:
Enum variant names are case-sensitive; should be 'Active' -> Option DQuick Check:
Variant names must match case exactly [OK]
- Using wrong case for variants
- Forgetting semicolons (not error here)
- Thinking variants need data always
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let msg = Message::Move { x: 10, y: 20 };
match msg {
Message::Quit => println!("Quit message"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
}
}What will this program print?
Solution
Step 1: Identify enum variant with data
The variablemsgisMessage::Move { x: 10, y: 20 }.Step 2: Match arms handle each variant
The match arm forMessage::Move { x, y }prints coordinates.Final Answer:
Move to (10, 20) -> Option AQuick Check:
Match prints coordinates for Move variant [OK]
- Confusing variant names
- Ignoring data inside variants
- Expecting compilation error incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
