Bird
Raised Fist0
Rustprogramming~10 mins

Why enums are used in Rust - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why enums are used
Define enum with variants
↓
Create variable of enum type
↓
Match variable to handle each variant
↓
Execute code based on variant
↓
End
Enums let us group related values under one type and handle each case clearly using match.
Execution Sample
Rust
enum Direction {
    Up,
    Down,
    Left,
    Right,
}

fn main() {
    let dir = Direction::Left;
    match dir {
        Direction::Up => println!("Going up!"),
        Direction::Down => println!("Going down!"),
        Direction::Left => println!("Going left!"),
        Direction::Right => println!("Going right!"),
    }
}
This code defines directions as enum variants and prints a message based on the chosen direction.
Execution Table
StepActionVariable/ValueMatch ConditionOutput
1Define enum Direction with variants Up, Down, Left, Right---
2Create variable dir with value Direction::Leftdir = Left--
3Match dir against Direction::Updir = LeftIs dir Up?No
4Match dir against Direction::Downdir = LeftIs dir Down?No
5Match dir against Direction::Leftdir = LeftIs dir Left?Yes
6Execute println!("Going left!")--Going left!
7Match ends after first true branch---
💡 Match ends after handling the Left variant, no further checks needed.
Variable Tracker
VariableStartAfter Step 2After Step 5Final
dirundefinedDirection::LeftDirection::LeftDirection::Left
Key Moments - 2 Insights
Why do we use match with enums instead of if-else?
Match checks all enum variants clearly and forces handling each case, unlike if-else which can miss cases. See execution_table rows 3-6 where each variant is checked.
Can enum variants hold different types of data?
Yes, enums can hold different data types per variant, making them flexible to represent complex states. This example uses simple variants, but Rust enums can store data too.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'dir' after step 2?
ADirection::Up
BDirection::Left
Cundefined
DDirection::Right
💡 Hint
Check the 'Variable/Value' column at step 2 in the execution_table.
At which step does the match find the correct variant and print the message?
AStep 3
BStep 5
CStep 6
DStep 7
💡 Hint
Look for the step where println! is executed in the execution_table.
If 'dir' was Direction::Up, which step would print the message?
AStep 3
BStep 4
CStep 6
DStep 5
💡 Hint
Step 3 matches against Direction::Up. If dir was Up, it would match yes and execute println!("Going up!") there.
Concept Snapshot
Enums group related values under one type.
Use match to handle each variant clearly.
Each variant can be a simple value or hold data.
Match forces handling all cases, avoiding errors.
Enums help write clear, safe code for choices.
Full Transcript
Enums in Rust let you define a type that can be one of several variants. This helps group related options together, like directions Up, Down, Left, Right. You create a variable of the enum type and assign it a variant. Then you use match to check which variant it is and run code accordingly. This way, your program handles all possible cases clearly and safely. The example shows defining Direction enum, creating a variable with Left, and matching it to print 'Going left!'. This approach avoids mistakes and makes code easier to understand.

Practice

(1/5)
1. Why are enums used in Rust programming?
easy
A. To group related values under one type name
B. To perform mathematical calculations faster
C. To store large amounts of unrelated data
D. To replace all functions with a single keyword

Solution

  1. Step 1: Understand the purpose of enums

    Enums allow grouping of related options or variants under one type name, making code organized.
  2. Step 2: Compare other options

    Options A, B, and D do not describe the main use of enums. Enums are not for math speed, unrelated data storage, or replacing functions.
  3. Final Answer:

    To group related values under one type name -> Option A
  4. Quick Check:

    Enums group related options = C [OK]
Hint: Enums group related choices under one name [OK]
Common Mistakes:
  • Thinking enums speed up math operations
  • Confusing enums with arrays or structs
  • Believing enums replace functions
2. Which of the following is the correct way to define an enum in Rust?
easy
A. enum Color { Red, Green, Blue }
B. enum Color = { Red, Green, Blue }
C. enum Color: Red, Green, Blue
D. enum Color -> { Red, Green, Blue }

Solution

  1. Step 1: Recall Rust enum syntax

    Rust enums are defined using the keyword enum followed by the name and curly braces containing variants separated by commas.
  2. Step 2: Check each option

    enum Color { Red, Green, Blue } matches correct syntax. Options A, B, and C use invalid symbols (=, :, ->) which are not part of enum syntax.
  3. Final Answer:

    enum Color { Red, Green, Blue } -> Option A
  4. Quick Check:

    Correct enum syntax uses braces and commas = D [OK]
Hint: Remember enum uses braces and commas, no equal sign [OK]
Common Mistakes:
  • Using '=' instead of braces
  • Using ':' or '->' after enum name
  • Omitting commas between variants
3. What will be the output of this Rust code?
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"),
    }
}
medium
A. Going North
B. Going East
C. Going South
D. Going West

Solution

  1. Step 1: Identify the enum variant assigned

    The variable dir is assigned Direction::East.
  2. Step 2: Match statement output

    The match checks dir and prints the string for the matching variant. Since dir is East, it prints "Going East".
  3. Final Answer:

    Going East -> Option B
  4. Quick Check:

    Match prints variant name = A [OK]
Hint: Match prints message for assigned enum variant [OK]
Common Mistakes:
  • Confusing variant names in match arms
  • Assuming default output without match
  • Ignoring enum variant assigned
4. Find the error in this Rust enum usage:
enum Status {
    Active,
    Inactive,
}

fn main() {
    let s = Status::active;
    match s {
        Status::Active => println!("Active"),
        Status::Inactive => println!("Inactive"),
    }
}
medium
A. Match arms should use lowercase variants
B. Missing semicolon after enum definition
C. Enum variants must be capitalized exactly
D. Enum cannot be used inside match statements

Solution

  1. Step 1: Check enum variant usage

    Rust enum variants are case sensitive and usually start with uppercase letters. The code uses Status::active instead of Status::Active.
  2. Step 2: Verify match arms and syntax

    Match arms use correct capitalization. No semicolon is needed after enum. Enums can be matched.
  3. Final Answer:

    Enum variants must be capitalized exactly -> Option C
  4. Quick Check:

    Enum variant names are case sensitive = A [OK]
Hint: Enum variants are case sensitive and capitalized [OK]
Common Mistakes:
  • Using lowercase enum variants
  • Adding unnecessary semicolons after enum
  • Thinking enums can't be matched
5. You want to represent a shape that can be either a Circle with a radius or a Rectangle with width and height. Why is using an enum the best choice in Rust?
hard
A. Because enums automatically calculate area for shapes
B. Because enums are faster than structs for storing data
C. Because enums store all shapes as the same data type without variants
D. Because enums can hold different data types for each variant safely

Solution

  1. Step 1: Understand enum variant data

    Rust enums can hold different data types for each variant, like a radius for Circle and width/height for Rectangle.
  2. Step 2: Compare other options

    Enums do not automatically calculate area (A), nor store all shapes as same data without variants (C). Speed (D) is not the main reason.
  3. Final Answer:

    Because enums can hold different data types for each variant safely -> Option D
  4. Quick Check:

    Enums hold variant-specific data = B [OK]
Hint: Enums hold different data per variant safely [OK]
Common Mistakes:
  • Thinking enums calculate values automatically
  • Confusing enums with structs storing same data
  • Assuming enums are always faster than structs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard