Defining Your First Enum
Create simple enumerated types.
What Is an Enum?
An enum (enumeration) lets you define a type by listing its possible values, called variants. A value of the type can only ever be one of those variants.
Enums shine when something has a fixed set of states, like the cardinal directions or the suits in a deck of cards.
enum Direction {
North,
South,
East,
West,
}Declaring an Enum
You declare an enum with the enum keyword, a name, and a comma-separated list of variants inside curly braces.
By convention enum names use PascalCase (like Direction), and so do the variant names (like North).
enum TrafficLight {
Red,
Yellow,
Green,
}All lessons in this course
- Defining Your First Enum
- Matching on Enum Variants
- Enums with Data
- Match Guards and Bindings