Generic enums in Rust - Time & Space Complexity
We want to understand how the time it takes to run code with generic enums changes as the input grows.
Specifically, how does using generic enums affect the number of steps the program takes?
Analyze the time complexity of the following code snippet.
enum Container<T> {
Single(T),
Pair(T, T),
}
fn process(container: Container<i32>) {
match container {
Container::Single(value) => println!("Value: {}", value),
Container::Pair(a, b) => println!("Sum: {}", a + b),
}
}
This code defines a generic enum with one or two values and a function that processes it by matching the enum variants.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Matching on enum variants and printing values.
- How many times: Exactly once per call, no loops or recursion.
Since the function processes one enum value at a time without loops, the steps stay the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The work does not increase with input size because there is no loop or recursion.
Time Complexity: O(1)
This means the time to run the code stays the same no matter how big the input is.
[X] Wrong: "Using generics or enums always makes the code slower as input grows."
[OK] Correct: Here, the generic enum just holds values and the code runs a simple match once, so time does not grow with input size.
Understanding how generic enums behave helps you explain how your code handles different data shapes efficiently, a useful skill in many coding tasks.
"What if the enum held a vector of values instead of one or two? How would the time complexity change?"