Enums
Enums define a type that can hold one of a fixed set of named values called variants. They are useful for representing states, directions, categories, and other discrete choices.
Defining an Enum
Enums are declared with the enum keyword followed by the name and an indented list of variant names.
enum Direction:
North
South
East
West
enum GameState:
Menu
Playing
Paused
GameOver Using Enum Values
Enum variants are accessed with dot notation on the enum name. A variable of an enum type can hold any variant of that enum.
let dir: Direction = Direction.North
let state: GameState = GameState.Playing Matching on Enums
The most common way to use an enum is with a match statement. Each case handles one or more variants. A default case handles all remaining variants.
fn describe(dir: Direction) -> str:
match dir:
case Direction.North:
return "moving north"
case Direction.South:
return "moving south"
case Direction.East:
return "moving east"
default:
return "moving west"