Skip to main content

enum

A named type whose values are listed in the declaration, each fixed to a literal of a primitive backing type.

enum TrackKind int32 {
    Air = 0;
    Surface = 1;
    Subsurface = 2;
}

Members​

Each member is a name, =, a literal, and a semicolon. The backing type follows the enum's name and is a primitive: bit, string, float32, float64, intN, or uintN.

  • An enum declares at least one member.
  • Member names are unique within the enum.
  • Each member's value must be assignable to the backing type.
  • Two members may carry the same value.
  • The value is a literal, so a negative member value does not parse.
  • A backing type that is not a primitive does not parse either.
enum SensorMode string {
    Search = "search";
    Track = "track";
}

enum Toggle bit {
    Off = false;
    On = true;
}

enum Priority uint8 {
    Low = 0;
    Default = 0;
    High = 2;
}

Values​

A member is reached through the enum, as TrackKind.Air. Its type is the enum, never the backing type — the backing type says what the members are written as, not what they convert to.

  • An enum value is not assignable to its backing type, and no cast converts one: value_cast requires a numeric source.
  • Equality compares members. Two members sharing one backing value are not equal.
  • A match over an enum covers it member by member.
enum TrackKind int32 {
    Air = 0;
    Surface = 1;
}

enum Priority uint8 {
    Low = 0;
    Default = 0;
}

function label(kind: TrackKind) -> string = match (kind) {
    TrackKind.Air => "air";
    TrackKind.Surface => "surface";
};

TrackKind.Air                       // => TrackKind.Air
label(TrackKind.Surface)            // => "surface"
Priority.Low == Priority.Default    // => false

Errors​

An enum with no members​

enum TrackKind int32 {}   // error: empty-enum

Two members with one name​

enum TrackKind int32 {
    Air = 0;
    Air = 1;   // error: duplicate-enum-member
}

A member value the backing type does not accept​

enum TrackKind int32 {
    Air = "air";   // error: enum-backing-type-mismatch
}

Using an enum value as its backing type​

An enum is a distinct type, so its members are not the integers they are written as.

enum TrackKind int32 {
    Air = 0;
    Surface = 1;
}

const kind_code: int32 = TrackKind.Air;   // error: type-mismatch
  • variant — a closed set of constructors that carry payloads.
  • const — naming one member for the rest of the module to use.