0PricingLogin
Learn Rust Coding · Lesson

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

  1. Defining Your First Enum
  2. Matching on Enum Variants
  3. Enums with Data
  4. Match Guards and Bindings
← Back to Learn Rust Coding