Chapter 13: Enums and Pattern Matching
Prerequisites
You will understand
- Sum types vs product types in memory
- Pattern matching with exhaustiveness
- Why
matchmust cover every variant
Reading time
25 min
+ 15 min exercises
You'll need this for Chapter 14
Option and Result are enums. Ch 14's entire error-handling model is built on the pattern matching you learn here.
Ch 14: Option & Result →
Type Shape
Product Types vs Sum Types
Exhaustiveness
Why `match` Feels Safer Than Ad Hoc Branching
Memory Layout
What an Enum Looks Like in Memory
Here is what a sum type looks like in memory: one tag, one payload slot, and a match that reads the tag.
Interactive simulation (requires JavaScript): an enum value is a discriminant tag plus a payload slot sized for the largest variant; match reads the tag, jumps to the right arm, and binds the payload — with exhaustiveness checked at compile time.