Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 13: Enums and Pattern Matching

Prerequisites

You will understand

  • Sum types vs product types in memory
  • Pattern matching with exhaustiveness
  • Why match must cover every variant

Reading time

25 min
+ 15 min exercises
Type Shape

Product Types vs Sum Types

Struct width AND height AND color Enum Circle OR Rectangle OR Point
Exhaustiveness

Why `match` Feels Safer Than Ad Hoc Branching

arm 1 → variant A arm 2 → variant B arm 3 → variant C arm 4 → variant D add a new variant → compiler finds every missing arm
Memory Layout

What an Enum Looks Like in Memory

Enum layout: discriminant + largest-variant data region Shape::Circle(5.0) tag 0u8 radius: f64 5.0 (8 bytes) padding unused total: 1 + max(variant data) + padding = 16 bytes Shape::Point tag 3u8 no variant data — space still reserved same allocation size as Circle Key insight Every variant of the same enum occupies the same number of bytes. The discriminant (tag) tells the runtime which variant is active. Layout similar to a tagged union in C.
The compiler stores an enum as a discriminant tag followed by data sized to the largest variant. Small variants waste some space, but the fixed layout makes pattern matching a constant-time tag check, not a search.

Step 1 - The Problem