Spec chapters

10. Enums, unions and switch

const Light = enum { red, yellow, green }
const Shape = union(enum) { circle: i64, rect: Size, empty }
  • An enum value is written Light.red, or .red where the type is known from context (a typed declaration, an argument, a return, a comparison). Otherwise .red is E115. Enums compare with == and print as their name.
  • A union value holds exactly one member. A member with a payload is written Shape{ .circle = 2 }; one without, .empty or Shape.empty. A union’s payload is read only with switch (E122 on u.circle).
  • Unions may have methods, like structs.
  • A member may be owned (a Buf, an owned struct); the union is then owned, and a switch over it may take the payload out (section 21).

switch is a statement over an enum or a union (E127 otherwise):

switch (shape) {
    .circle => |r| { ... }          // |r| binds the payload
    .rect, .empty => { ... }        // several members, no capture
    else => { ... }                 // anything not listed; must be last
}

It must handle every member exactly once, or end with else; an else that can never run is also an error (E127). break and continue in an arm act on the enclosing loop.

// expect: 24
// expect: green
uses io

fn main(io: Io) void {
    const shapes = [3]Shape{ Shape{ .circle = 2 }, Shape{ .rect = Size{ .w = 3, .h = 4 } }, .empty }
    var total = 0
    for (shapes) |s| {
        total = total + s.area()
    }
    io.print(total)
    io.print(next(.red))
}

const Size = struct { w: i64, h: i64 }

const Shape = union(enum) {
    circle: i64
    rect: Size
    empty

    fn area(self: Shape) i64 {
        switch (self) {
            .circle => |r| {
                return 3 * r * r
            }
            .rect => |sz| {
                return sz.w * sz.h
            }
            .empty => {
                return 0
            }
        }
    }
}

const Light = enum { red, yellow, green }

fn next(l: Light) Light {
    switch (l) {
        .red => {
            return .green
        }
        else => {
            return .red
        }
    }
}
// error: E127
uses io

const Light = enum { red, green }

fn main(io: Io) void {
    switch (Light.red) {
        .red => {
            io.print(1)
        }
    }
}