← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 1 of 7

Enum Basics

An enum lets a value be exactly one of several named choices you define ahead of time.
Syntax
rust
enum Name {
    Variant1,
    Variant2(Type),
    Variant3 { field: Type },
}

let value = Name::Variant1;

Defining a Simple Enum

An enum defines a type whose value can be exactly one of a fixed set of named variants, useful for representing a closed set of possibilities.

Example: Defining a Simple Enum

markup
// Auto-generate #[derive(Debug)] for the type below
#[derive(Debug)]
// Define an enum `Direction` listing its possible variants
enum Direction {
    North,
    South,
    East,
    West,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `heading`, set to `Direction::North`
    let heading = Direction::North;
    // Print "{:?}" to the console, substituting in `heading` (with a trailing newline)
    println!("{:?}", heading);
}

Enums With Data

Unlike simple labels, Rust enum variants can carry their own associated data, and different variants can carry different types and amounts of data.

Example: Enums With Data

markup
// Auto-generate #[derive(Debug)] for the type below
#[derive(Debug)]
// Define an enum `Shape` listing its possible variants
enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `shapes`, set to `[Shape::Circle(2.0), Shape::Rectangle(3.0, 4.0)]`
    let shapes = [Shape::Circle(2.0), Shape::Rectangle(3.0, 4.0)];
    // Loop over `shapes.iter()`, binding each item to `s`
    for s in shapes.iter() {
        // Print "{:?}" to the console, substituting in `s` (with a trailing newline)
        println!("{:?}", s);
    }
}

Matching on an Enum

match is the primary way to inspect which variant an enum value holds and to extract any data it carries, with a separate arm for each possible variant.

Example: Matching on an Enum

markup
// Define an enum `TrafficLight` listing its possible variants
enum TrafficLight {
    Red,
    Yellow,
    Green,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `light`, set to `TrafficLight::Yellow`
    let light = TrafficLight::Yellow;
    // Match on `light` and branch by pattern
    match light {
        TrafficLight::Red => println!("Stop"),
        TrafficLight::Yellow => println!("Slow down"),
        TrafficLight::Green => println!("Go"),
    }
}

Comparing Enum Values

Deriving PartialEq on an enum allows comparing its values directly with ==, which is useful for simple checks without writing a full match.

Example: Comparing Enum Values

markup
// Auto-generate #[derive(PartialEq, Debug)] for the type below
#[derive(PartialEq, Debug)]
// Define an enum `Status` listing its possible variants
enum Status {
    Active,
    Inactive,
}

// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `current`, set to `Status::Active`
    let current = Status::Active;
    // Print "Is active: {}" to the console, substituting in `current == Status::Active` (with a trailing newline)
    println!("Is active: {}", current == Status::Active);
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting an enum variant can carry its own data, not just be a plain label like in some other languages.
  2. Trying to compare enum variants with == before deriving PartialEq on the enum.
  3. Assuming enum variant names are globally unique -- they must be qualified with EnumName::Variant unless imported.
Chapter Summary
  • An enum defines a type that can be exactly one of several named variants.
  • Variants can optionally carry associated data, including different data per variant.
  • Enum values are typically handled with match to branch on which variant is present.
  • Deriving traits like Debug and PartialEq on an enum enables printing and comparison.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.