Skip to content
Guest
Rust · Course Syllabus Show lessons
Types & Patterns · 10 min read · Intermediate

Algebraic Enums & Exhaustive match

Encode rich domain states using enums with attached data and let exhaustive match catch missing cases at compile time.

What you'll learn

  • Attach different payload types to each enum variant
  • Use exhaustive match expressions that refuse to compile if a variant is forgotten
  • Use if let for concise single-variant matching

Overview

Encode rich domain states using enums with attached data and let exhaustive match catch missing cases at compile time.

Code Example

enum Status {
    Draft,
    Published { views: u64 },
}

fn describe(s: Status) -> String {
    match s {
        Status::Draft => "Draft".into(),
        Status::Published { views } => format!("Live ({views} views)"),
    }
}

Key Takeaways

  • Attach different payload types to each enum variant
  • Use exhaustive match expressions that refuse to compile if a variant is forgotten
  • Use if let for concise single-variant matching

Quick Check

Check Your Understanding

Score: 0 / 1

1. What happens if you add a new variant to a Rust `enum` and forget to handle it in an existing `match` expression?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind