Lynxer

Documentation

Enums

An enum is a tagged union: a fixed set of variants, each optionally carrying typed named fields. Declare it at the top level, before main.

Declaration

enum status = [
    Ready,
    Failed(str reason)
]{}

Construction

any a = status.Ready;
any b = status.Failed("disk");

A payload field is read like a record field:

println(b.reason);   // disk

An enum value prints as Enum.Variant (println(a) prints status.Ready).

Matching with switch

An enum value is normally consumed with a switch pattern, which destructures the payload and binds the field names for the case body:

func describe(status value) -> str {
    switch (value) {
        case(status.Ready){ return "ready"; }
        case(status.Failed(reason)){ return "failed: " + reason; }
    }
    return "unknown";
}

See language for the general switch form.

Equality is identity, not structure

Enum values compare by identity, so two separately built variants are never equal — even two Readys, and even a variant compared with itself after a round trip:

println(status.Ready is status.Ready);          // false
println(status.Failed("x") is status.Failed("x")); // false

any a = status.Ready;
println(a is a);                                // true

Use switch patterns to test which variant a value is; do not use is.

Full example

global setup(){}

enum status = [
    Ready,
    Failed(str reason)
]{}

func describe(status value) -> str {
    switch (value) {
        case(status.Ready){ return "ready"; }
        case(status.Failed(reason)){ return "failed: " + reason; }
    }
    return "unknown";
}

global main(){
    any a = status.Ready;
    any b = status.Failed("disk");
    println(a);              // status.Ready
    println(b.reason);       // disk
    println(describe(a));    // ready
    println(describe(b));    // failed: disk
}

See also