0
0
Rustprogramming~5 mins

Generic enums in Rust - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic enums
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
101
1001
10001

Pattern observation: The work does not increase with input size because there is no loop or recursion.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays the same no matter how big the input is.

Common Mistake

[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.

Interview Connect

Understanding how generic enums behave helps you explain how your code handles different data shapes efficiently, a useful skill in many coding tasks.

Self-Check

"What if the enum held a vector of values instead of one or two? How would the time complexity change?"