Docs/Language guide

Enums & matching

Construct tagged enum values, extract immutable payloads, and match variants.

Declare and construct variants#

An enum defines a type whose value holds exactly one of its named alternatives, called variants. A variant may carry no data, an ordered list of values (a tuple payload), or named fields (a record payload). Variant names belong to the enum. Tuple construction uses parentheses; record construction uses braces with positional values or named fields. Payload fields are immutable. Uppercase enum and variant names are exported to other packages.

Ocean
enum GuiEvent {
    GuiLoad,
    KeyPress(i8),
    Click{x, y i8},
}

func main() {
    load := GuiEvent.GuiLoad;
    key := GuiEvent.KeyPress(65);
    click := GuiEvent.Click{x: 2, y: 3};
}

Test and extract a payload#

Compare an enum value with a qualified variant name, such as event == GuiEvent.KeyPress, to test which variant it holds. This test does not compare the payload data. Extract data with value.(Enum.Variant). A tuple yields its positional values; use multiple assignment for multiple elements and _ to discard positions. A record yields a record with immutable fields. An extraction traps if the value holds a different variant.

Comparing two constructed enum values compares their tags and payloads recursively. A comparison with a qualified variant selector still tests only the tag.

Ocean
func keyCode(event GuiEvent) i8 {
    if (event == GuiEvent.KeyPress) {
        key := event.(GuiEvent.KeyPress);
        return key;
    }
    return 0;
}

Match variants#

match evaluates its enum subject once and executes the matching arm. Tuple bindings follow payload order. A record pattern chooses fields by name and may omit fields it does not need. In an alias such as clickX = x, the name on the left is the new local binding and the name on the right is the payload field to read. Each arm has its own scope. The compiler warns when variants are missing; an arm naming the enum type supplies a default. Use match to choose among enum variants. A type-guard switch chooses among concrete types stored in interfaces and is not a replacement for matching an enum.

Ocean
func position(event GuiEvent) int {
    match (event) {
        GuiEvent.GuiLoad => return 0;
        GuiEvent.KeyPress(_) => return 1;
        GuiEvent.Click{clickX = x, clickY = y} => {
            return clickX->int + clickY->int;
        }
    }
    return 0;
}

Extract named fields#

A named record extraction can select only the fields you need. The names on the left of the declaration or assignment match the binding names in the pattern, so field order does not matter. An alias gives a field a different local name.

Ocean
func clickX(event GuiEvent) int {
    if (event == GuiEvent.Click) {
        x, y := event.(GuiEvent.Click{y, x});
        clickX, clickY := event.(GuiEvent.Click{clickY = y, clickX = x});
        return x->int + clickX->int;
    }
    return 0;
}

In the first extraction, local x receives payload field x and local y receives field y, even though the pattern lists y first. In the second, clickX = x gives field x the local name clickX. The aliases describe field-to-binding relationships, not positional pairing.

Fixed payload variants#

A variant can define a fixed payload with := and an inferred type, or with : Type = and an explicit type. Accessing that variant constructs a value carrying the payload. For example, Number.One is a value of enum type Number carrying the integer payload 1; it is not an ordinary int. The variant name remains part of the enum value’s identity even if another variant carries the same data.

Ocean
struct RGB { r, g, b int; }
enum Color {
    Red: RGB = {255, 0, 0},
    Green: RGB = {0, 255, 0},
    Blue := RGB{0, 0, 255},
    Other(RGB),
}
enum Number { One := 1, Two := 2, Other(int) }

Enum methods#

Enums support value and pointer receiver methods. Generic receiver arguments bind the enum's type parameters; methods may also declare their own explicit type parameters. Value receivers copy the enum, while pointer receivers can replace an addressable enum value. Declare methods in the package that defines the enum. Method names cannot collide with any variant name or named payload field.

Ocean
func (r Result<T>) unwrap() T {
    match (r) {
        Result.value(v) => return v;
        Result.error(msg) => return panic msg;
    }
    return zero(T);
}

// result := Result<int>.value(42);
// value := result.unwrap();

Generic enums#

Enums accept type parameters and constraints, using the same syntax as structs. Specify arguments when constructing a value, such as Result<int>.value(42). Supplying type arguments chooses a concrete version of the generic enum, called a specialization. Result<int> carries integer successes and Result<string> carries string successes. They are different types, so a variable declared as one cannot receive a value of the other. Payloads may use type parameters in tuple and record fields, and enums may be nested or passed through generic functions.

Ocean
enum Result<T> {
    value(T),
    error(string),
}

func unwrap<T>(result Result<T>, fallback T) T {
    match (result) {
        Result.value(v) => return v;
        Result.error(_) => return fallback;
    }
    return fallback;
}

func main() int {
    result := Result<int>.value(42);
    value := result.(Result<int>.value);
    return unwrap<int>(result, 0);
}

Built-in Optional<T>#

Optional<T> is available without imports or standard-library files. Its variants are Optional<T>.value(value), carrying one T, and Optional<T>.none, carrying no payload. none equals null; assigning null selects none. Uninitialized optionals and zero(Optional<T>) are none. value(null) remains present when T is nullable. The hasValue() bool method returns true for value (including value(null)) and false for none. The unwrap() T method returns the value payload (including null) and panics on none, attributed to the caller. Returned payloads follow normal value-copy and ownership rules. Normal enum equality, extraction, match, and ownership apply. The lowercase variants and methods are public built-ins, independent of package capitalization rules. A user declaration can shadow Optional.

Ocean
func main() int {
    value: Optional<int> = null;
    if (value != null) return 1;
    value = Optional<int>.value(42);
    match (value) {
        Optional.value(n) => return n - 42;
        Optional.none => return 2;
    }
    return 3;
}

Built-in Result<T>#

Result<T> is available without imports or standard-library files. It is the compiler-owned equivalent of enum Result<T> { value(T), error(string) }. The built-in value and error variants, and its lowercase helper methods such as unwrap, are available to every package. This is a specific property of the compiler-provided Result; user-defined lowercase declarations still follow normal package privacy rules.

Construct Result<int>.value(42) or Result<int>.error("invalid number"). Normal comparisons, extraction and match work with these variants. A user-declared Result may shadow the name and remains a distinct type. Payloads and fallbacks retain ordinary value ownership. result.error() returns the stored error string and panics on a successful value; Result<T>.error(message) still constructs an error variant. This built-in accessor is an exception to the rule against methods sharing enum variant names.

Built-in Result<T> reference
Methodvalue caseerror case
hasError() boolReturn falseReturn true
error() stringPanicReturn stored error string
unwrap() TReturn payloadReturn a panic with the stored error string, attributed to caller
unwrapOrElse(fallback T) TReturn payloadReturn provided fallback value
unwrapOrZero() TReturn payloadReturn zero(T)
Ocean
func main() int {
    success := Result<int>.value(42);
    failure := Result<int>.error("invalid number");
    if (failure.unwrapOrZero() != 0) return 1;
    return success.unwrap() + failure.unwrapOrElse(0);
}

Fallback evaluation and zero values#

unwrapOrElse takes an already evaluated fallback value, not a function to call later. For example, result.unwrapOrElse(computeFallback()) calls computeFallback() even when result contains a successful value. Use an explicit match if computing the fallback should happen only on error. unwrapOrZero follows the existing zero(T) semantics; a pointer zero is a zero address and remains distinct from explicit null.

Built-in methods appear in editor completion and hover. Their compiler-owned declarations cannot be renamed and do not navigate to a physical source file.