Skip to content

Enums & Sum Types

Enums

Weld enums are proto-style: each variant declares a number (required) and an optional string (defaulting to the name). A zero Unspecified value always exists and is the fallback when reinterpreting an unknown number or string. Enums serialize as their string; int(e) / str(e) and Role(n) / Role(s) reinterpret both ways.

weld
enum Role {
    # Unspecified = 0 : "unspecified" is implicit
    Admin = 1 : "admin",
    User  = 2 : "user",
}

type Account = {
    id: int,
    role: Role,        # enum field → JSON string
}

route GET "/accounts/:id" (id: int) -> Account {
    respond Account { id: id, role: Role.Admin }
}

# Reinterpret a path string into an enum, then back to int/string
route GET "/role/:name" (name: string) {
    let r = Role(name)                 # string -> enum (unknown -> Unspecified)
    respond "name={name} number={int(r)} string={str(r)}\n"
}

Enums become TypeScript string enums in the generated client.

The built-in std enums

Some enums ship with the language under the std namespace: std.MimeType (well-known content types) and std.HttpStatus (named status codes). Write type std.MimeType.Json / status std.HttpStatus.NotFound instead of a mis-spellable "application/json" / 404. They're ordinary proto-style enums (str(std.MimeType.Html)"text/html; charset=utf-8"), need no declaration or import, and only show up in the generated code when you use them.

Sum types

A type is either a record ({ … }) or a sum — a tagged union whose variants carry positional payloads. Construct a variant qualified (Shape.Circle(2.0)); match it unqualified, binding the payload, and the match must be exhaustive.

weld
type Shape =
    | Circle(float)
    | Rect(float, float)
    | Empty                       # nullary variant

fn area(s: Shape) -> float {
    return match s {
        Circle(r)  => 3.14159 * r * r,
        Rect(w, h) => w * h,       # multi-value payload binds positionally
        Empty      => 0.0,
    }
}

route GET "/shape/:kind/:x" (kind: string, x: float) -> Shape {
    respond match kind { "circle" => Shape.Circle(x), _ => Shape.Empty }
}

A sum type compiles to a Zig union(enum) (zero-overhead). A responded sum value auto-encodes as {"tag":"Circle","values":[2.0]} (a nullary variant gives "values":[]).

Sum types also power typed errors: a function can declare an error type with -> T ! E where E is a sum type.