Bird
Raised Fist0
Rustprogramming~10 mins

Defining enums in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Defining enums
Start
↓
Define enum with variants
↓
Create variable of enum type
↓
Use enum variable in code
↓
Match or access enum variant
↓
End
This flow shows how to define an enum, create a variable of that enum type, and then use it in code.
Execution Sample
Rust
enum Direction {
    North,
    East,
    South,
    West,
}

fn main() {
    let dir = Direction::East;
}
Defines an enum Direction with four variants and creates a variable dir set to East.
Execution Table
StepActionCode LineResult/State
1Define enum Direction with variants North, East, South, Westenum Direction { North, East, South, West }Enum Direction created with 4 variants
2Create variable dir of type Direction and assign East variantlet dir = Direction::East;dir = Direction::East
3Program ready to use dir as Direction::EastN/Adir holds East variant
💡 Enum defined and variable assigned; program ready for further use.
Variable Tracker
VariableStartAfter Step 2Final
dirundefinedDirection::EastDirection::East
Key Moments - 2 Insights
Why do we write Direction::East instead of just East?
Because East is a variant inside the enum Direction, we use :: to specify it belongs to Direction, as shown in execution_table step 2.
Can we assign a string or number directly to dir?
No, dir must be assigned one of the enum variants defined in Direction, like Direction::East in execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of dir after step 2?
Aundefined
BEast
CDirection::East
DDirection
💡 Hint
Check the 'Result/State' column in row for step 2 in execution_table.
At which step is the enum Direction created?
AStep 2
BStep 1
CStep 3
DAfter all steps
💡 Hint
Look at the 'Action' column in execution_table for when enum is defined.
If we tried to assign dir = East without Direction::, what would happen?
ACompiler error: unknown variant East
Bdir would be a string
CIt would work fine
Ddir would be an integer
💡 Hint
Refer to key_moments about why Direction::East is needed.
Concept Snapshot
Defining enums in Rust:
enum Name { Variant1, Variant2, ... }
Create variable: let var = Name::Variant1;
Use :: to access variants.
Enum variants are distinct types.
Cannot assign other types directly.
Full Transcript
This example shows how to define an enum called Direction with four variants: North, East, South, and West. Then, it creates a variable dir and assigns it the East variant using Direction::East. The execution table traces these steps, showing the enum creation and variable assignment. The variable tracker shows how dir changes from undefined to Direction::East. Key moments clarify why we use Direction::East and that we cannot assign other types directly. The quiz tests understanding of these points. The snapshot summarizes the syntax and rules for defining and using enums in Rust.

Practice

(1/5)
1. What is the main purpose of defining an enum in Rust?
easy
A. To create a function that returns multiple values
B. To write a loop that iterates over numbers
C. To define a variable that can only hold integers
D. To group related values under one type name

Solution

  1. Step 1: Understand what enums represent

    Enums group related values under a single type name, making code clearer and safer.
  2. Step 2: Compare options with enum purpose

    Only To group related values under one type name correctly describes grouping related values under one type name.
  3. Final Answer:

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

    Enums = Group related values [OK]
Hint: Enums group related values under one name [OK]
Common Mistakes:
  • Thinking enums are for loops or functions
  • Confusing enums with variables or constants
  • Believing enums only hold integers
2. Which of the following is the correct syntax to define a simple enum named Color with variants Red, Green, and Blue?
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 use curly braces with comma-separated variants, no equals or semicolons.
  2. Step 2: Check each option

    enum Color { Red, Green, Blue } matches correct syntax: enum Color { Red, Green, Blue }.
  3. Final Answer:

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

    Enum syntax = curly braces with commas [OK]
Hint: Use curly braces and commas for enum variants [OK]
Common Mistakes:
  • Using '=' instead of braces
  • Separating variants with semicolons
  • Using colon ':' after enum name
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 South
B. Going North
C. Going East
D. Going West

Solution

  1. Step 1: Identify the enum variant assigned

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

    The match arm for Direction::East prints "Going East".
  3. Final Answer:

    Going East -> Option C
  4. Quick Check:

    Match on Direction::East prints "Going East" [OK]
Hint: Match enum variant to print correct message [OK]
Common Mistakes:
  • Confusing variant names in match arms
  • Forgetting to use enum name with variants
  • Assuming default output without match
4. Identify the error in this enum definition:
enum Status {
    Active,
    Inactive,
    Pending()
}
medium
A. Enum variants must all have parentheses
B. The variant 'Pending' should not have parentheses unless it holds data
C. Enum name cannot be 'Status'
D. Missing semicolon after enum definition

Solution

  1. Step 1: Check variant syntax

    Variants without data should not have parentheses; 'Pending()' is incorrect here.
  2. Step 2: Confirm correct enum variant style

    Only variants holding data use parentheses; others are simple names.
  3. Final Answer:

    The variant 'Pending' should not have parentheses unless it holds data -> Option B
  4. Quick Check:

    Simple variants = no parentheses [OK]
Hint: Only use parentheses for variants holding data [OK]
Common Mistakes:
  • Adding empty parentheses to simple variants
  • Thinking all variants need parentheses
  • Confusing enum name rules
5. Given this enum with data:
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

Which code correctly creates a Message variant to move to coordinates (10, 20)?
hard
A. let msg = Message::Move { x: 10, y: 20 };
B. let msg = Message::Move(10, 20);
C. let msg = Message::Move(10, y: 20);
D. let msg = Message::Move { 10, 20 };

Solution

  1. Step 1: Understand the variant type

    The variant Move uses named fields inside braces: { x: i32, y: i32 }.
  2. Step 2: Match correct syntax for named fields

    let msg = Message::Move { x: 10, y: 20 }; uses correct syntax with field names and values: Move { x: 10, y: 20 }.
  3. Final Answer:

    let msg = Message::Move { x: 10, y: 20 }; -> Option A
  4. Quick Check:

    Named fields need braces and field names [OK]
Hint: Use braces and field names for struct-like enum variants [OK]
Common Mistakes:
  • Using tuple syntax for struct-like variants
  • Omitting field names inside braces
  • Mixing tuple and struct variant syntax
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