TExcelTAD
Home › Zig › Zig Enums

Zig Enums

An enum is a type with a fixed list of named values: the days of the week, the states of a traffic light, the suits in a deck of cards. Using an enum instead of magic numbers or strings makes code self-documenting, and the compiler can check that a switch handles every case.

Declaring and using an enum

zig · try it yourself
const std = @import("std");

const Direction = enum { north, east, south, west };

pub fn main() void {
    var heading = Direction.north;
    std.debug.print("heading: {t}\n", .{heading});

    heading = .east; // the type is known, so the name can be left out
    std.debug.print("heading: {t}\n", .{heading});
    std.debug.print("is east? {}\n", .{heading == .east});
}
heading: north
heading: east
is east? true

The leading-dot form .east is an enum literal: whenever Zig already knows the expected enum type, you can omit the type name. {t} prints the tag name.

Exhaustive switch

The most important feature of enums: a switch over an enum must handle every member, and it needs no else:

zig · try it yourself
const std = @import("std");

const Direction = enum { north, east, south, west };

fn turnRight(d: Direction) Direction {
    return switch (d) {
        .north => .east,
        .east => .south,
        .south => .west,
        .west => .north,
    };
}

pub fn main() void {
    var d = Direction.west;
    for (0..5) |_| {
        std.debug.print("{t} -> ", .{d});
        d = turnRight(d);
    }
    std.debug.print("{t}\n", .{d});
}
west -> north -> east -> south -> west -> north

If you later add up to Direction, every switch without it stops compiling — the compiler finds all the places you need to update.

Integer values

Each enum member has an integer value, counting from 0. You can choose the integer type and set values explicitly, then convert with @intFromEnum and @enumFromInt:

zig · try it yourself
const std = @import("std");

const HttpStatus = enum(u16) {
    ok = 200,
    created = 201,
    not_found = 404,
    server_error = 500,
};

pub fn main() void {
    const s = HttpStatus.not_found;
    std.debug.print("{t} = {d}\n", .{ s, @intFromEnum(s) });

    const from_number: HttpStatus = @enumFromInt(201);
    std.debug.print("201 is {t}\n", .{from_number});
    std.debug.print("as text: {s}\n", .{@tagName(HttpStatus.server_error)});
}
not_found = 404
201 is created
as text: server_error

@enumFromInt with a number that is not a member panics in safe builds. When the input comes from outside (a file, the network), use std.meta.intToEnum, which returns an error instead.

Methods on enums

Enums can contain functions, just like structs. This keeps behaviour next to the data it describes:

zig · try it yourself
const std = @import("std");

const Size = enum {
    small,
    medium,
    large,

    fn priceCents(self: Size) u32 {
        return switch (self) {
            .small => 250,
            .medium => 320,
            .large => 390,
        };
    }

    fn next(self: Size) ?Size {
        return switch (self) {
            .small => .medium,
            .medium => .large,
            .large => null,
        };
    }
};

pub fn main() void {
    const order = [_]Size{ .large, .small, .small, .medium };
    var total: u32 = 0;
    for (order) |s| total += s.priceCents();
    std.debug.print("total: {d} cents\n", .{total});

    var s: ?Size = .small;
    while (s) |size| : (s = size.next()) {
        std.debug.print("{t} ", .{size});
    }
    std.debug.print("\n", .{});
}
total: 1210 cents
small medium large 

Iterating over all members

std.enums.values gives every member of an enum as a slice, which is handy for menus and tables:

zig · try it yourself
const std = @import("std");

const Planet = enum { mercury, venus, earth, mars };

pub fn main() void {
    for (std.enums.values(Planet)) |p| {
        std.debug.print("{d}: {t}\n", .{ @intFromEnum(p), p });
    }
    std.debug.print("{d} planets listed\n", .{std.enums.values(Planet).len});
}
0: mercury
1: venus
2: earth
3: mars
4 planets listed

Non-exhaustive enums

An enum whose last member is _ is non-exhaustive: it accepts integer values that have no name. This is used for protocols that may gain new codes in the future. Switches over such enums need an else or _ branch.

zig
const Opcode = enum(u8) { nop = 0, jump = 1, halt = 0xff, _ };

Summary

Feature Syntax
declare const E = enum { a, b };
choose integer type enum(u8) { a = 1, b = 7 }
literal E.a or .a
name as text @tagName(x) or {t}
to / from integer @intFromEnum(x), @enumFromInt(n)
all members std.enums.values(E)

Test yourself

Why can you write .east instead of Direction.east in d = .east;?

  1. Enums are global
  2. The expected type is already known from d
  3. It is a string
  4. Dots are optional everywhere

What does @intFromEnum(Color.blue) return for enum { red, green, blue }?

  1. 0
  2. 1
  3. 2
  4. 3

What happens if you add a member to an enum and a switch over it doesn't handle it?

  1. Nothing
  2. Runtime panic when reached
  3. Compile error until the switch is updated
  4. The else branch is added automatically