Introduction: What is an Enum?#
Enums (Enumerations) in Rust are custom data types that allow you to represent a value that can be one of several possible variants.
If you have prior experience with Java or C++, you probably used enums to define simple sets of constants (such as days of the week). In Rust, however, enums are vastly more capable: each variant can hold heterogeneous data of different shapes and types, making your code safe, expressive, and concise.
Constructing Variants#
Unlike many languages where enums are simply named integer constants under the hood, Rust enum variants can store rich data structures. A single enum can hold three distinct variant flavors:
- Unit variants: without associated data (similar to unit structs).
- Tuple variants: with unnamed payload data in parentheses (similar to tuple structs).
- Struct variants: with named fields inside curly braces
{}(similar to traditional structs).
Let’s explore how variants are declared, what an uninhabited type represents, and how data is extracted using match in the interactive slides below:
Implementation Details:#
- Step 1. Variant Flavors: The
WebEventenum demonstrates all three variant forms. An important detail: all fields and payloads defined within enum variants are automatically public; you do not need to prefix them withpub. - Step 2. Empty Enums (Uninhabited Types): Rust allows defining an
enumwithout any variants at all (e.g.,enum EmptyEnum {}). It is impossible to instantiate this type in safe code. Such types help represent states that should never occur, allowing the compiler to optimize unreachable execution paths. - Step 3. Extracting Data (Pattern Matching): Because different variants can hold entirely different data types, the compiler will not allow direct access without inspection. We must determine which variant is currently active. The most expressive way to do this is using the
matchexpression.
Important: The
matchexpression in Rust is exhaustive. The compiler will produce an error if even a single enum variant is left unhandled.
Test Your Knowledge#
Take a quick interactive quiz to solidify your understanding of Rust enums:
