typestar

Enums in Zig

A cargo enum with its own method, exhaustively switched.

const std = @import("std");

const Cargo = enum {
    general,
    reefer,
    hazmat,

    fn stowage(self: Cargo) []const u8 {
        return switch (self) {
            .general => "any hold",
            .reefer => "plug it in",
            .hazmat => "deck only",
        };
    }
};

pub fn main() void {
    const load: Cargo = .reefer;
    std.debug.print("{s} -> {s}\n", .{ @tagName(load), load.stowage() });
}

How it works

  1. The enum declares three tags; .reefer names one with the leading dot.
  2. The method's switch (self) must cover every tag — add one and this fails to compile.
  3. @tagName turns the tag back into its source-code spelling.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
339
Tokens
110
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 94 seconds.

Type this snippet

Step 2 of 3 in Structs & enums, step 14 of 27 in Language basics.

← Previous Next →

Enums in other languages