Enums

Basic enums

tape
enum Direction : u8 {
    North = 0;
    East = 1;
    South = 2;
    West = 3;
}

let facing: Direction = Direction.North;

Enums with descriptions

tape
enum HttpStatus : u16 {
    Ok = 200: "success";
    NotFound = 404: "not found";
    ServerError = 500: "internal server error";
}

The description string is accessible at runtime:

tape
let msg: string = HttpStatus.desc(HttpStatus.NotFound);
// "not found"

Backing type

The : u8 suffix specifies the underlying integer type. Any integer type works:

tape
enum BigEnum : u32 {
    First = 0;
    Last = 0xFFFFFFFF;
}

Matching on enums

Use match to branch on enum values:

tape
match (facing) {
    Direction.North => { move(0, -1); }
    Direction.East => { move(1, 0); }
    Direction.South => { move(0, 1); }
    Direction.West => { move(-1, 0); }
}

Use _ as a wildcard catch-all:

tape
match (facing) {
    Direction.North => { move(0, -1); }
    _ => { io.println("not north"); }
}

Match must be exhaustive — all variants must be covered, or _ must be present.

As error types

Enums are commonly used as error types with T or E:

tape
enum ParseErr : u8 {
    BadInput = 1: "invalid input";
    Overflow = 2: "value too large";
}

fn parse(s: string) -> i64 or ParseErr {
    // ...
}

Last modified: