Chapter 10: Enums and Pattern Matching

Rust’s enums (enumerations) allow you to define a type by enumerating its possible variants. These variants can range from simple symbolic names, much like C enums, to variants holding complex data structures, combining the flexibility of C unions with Rust’s type safety. Rust integrates these capabilities into a single, powerful feature, significantly enhancing what C offers through separate enum and union constructs. In programming language theory, such types are often called algebraic data types, sum types, or tagged unions, concepts shared with languages like Haskell, OCaml, and Swift.

We will explore how Rust enums improve upon C’s approach, demonstrating their role in creating robust and expressive code. We will also introduce pattern matching, primarily through the match expression, which is Rust’s main mechanism for working with enums safely and concisely.