Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Types and Memory

Enums and Unions

Learn Zig enums and unions: enum values and backing types, methods on enums, @tagName and @intFromEnum, bare and tagged unions, switch with captures, and modeling states safely.

Enums and unions let you describe data that can be one of several things. An enum picks one name from a fixed list (red, green, blue). A union picks one of several shapes of data (an integer, or a string, or nothing). Combined with switch, they are how Zig programs model states, commands, tokens, shapes and results without flags and magic numbers.

Enums

ZIG
const std = @import("std");

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

pub fn main() void {
    const d = Direction.east;
    std.debug.print("{s}\n", .{@tagName(d)});         // east
    std.debug.print("{d}\n", .{@intFromEnum(d)});      // 1
}

Values are named with a leading dot (.east) when the type is known from context. By default the compiler picks the smallest integer that fits; the first value is 0. @tagName gives the name as a string, @intFromEnum the number, and @enumFromInt converts back (checked in safe modes).

Explicit values and backing types

ZIG
const HttpStatus = enum(u16) {
    ok = 200,
    not_found = 404,
    server_error = 500,
    _,                          // non-exhaustive: other values allowed
};

enum(u16) fixes the integer type, which matters for file formats, C interop and network protocols. A trailing _ makes the enum non-exhaustive: any integer converts to it, and a switch then requires an else prong. Leave it out when the list is closed.

Methods and declarations

Enums are namespaces like structs, so they can have functions and constants:

ZIG
const Light = enum {
    red,
    yellow,
    green,

    fn next(self: Light) Light {
        return switch (self) {
            .red => .green,
            .green => .yellow,
            .yellow => .red,
        };
    }
};

pub fn main() void {
    var light = Light.red;
    for (0..4) |_| {
        std.debug.print("{s} ", .{@tagName(light)});
        light = light.next();
    }
    std.debug.print("\n", .{});
}

Output: red green yellow red .

Because switch over an enum must be exhaustive, adding a fourth light later makes the compiler flag every function that forgot to handle it.

Parsing enums from text

std.meta.stringToEnum(Light, "green") returns an optional ?Light: the enum value if the string matches a field name, or null otherwise. That is the simple way to parse commands and configuration.

Unions

A union holds one of several fields at a time, sharing the same memory. A bare union does not remember which field is active; reading the wrong one is undefined behavior. You almost always want a tagged union, where the active field is tracked:

ZIG
const Value = union(enum) {
    int: i64,
    float: f64,
    text: []const u8,
    nothing,
};

union(enum) creates a hidden enum tag automatically, with one tag per field. A field with no payload (nothing) has type void. Create values with the field name:

ZIG
const a = Value{ .int = 42 };
const b = Value{ .text = "hello" };
const c: Value = .nothing;

Switching on a tagged union

switch unwraps the payload with a capture. This is the only safe way to read a union:

ZIG
fn describe(v: Value) void {
    switch (v) {
        .int => |n| std.debug.print("integer {d}\n", .{n}),
        .float => |f| std.debug.print("float {d:.2}\n", .{f}),
        .text => |s| std.debug.print("text \"{s}\"\n", .{s}),
        .nothing => std.debug.print("nothing\n", .{}),
    }
}

pub fn main() void {
    describe(.{ .int = 42 });
    describe(.{ .float = 3.14159 });
    describe(.{ .text = "hello" });
    describe(.nothing);
}
TEXT
integer 42
float 3.14
text "hello"
nothing

Accessing the wrong field directly (v.int when the tag is .text) is a safety-checked panic in Debug and ReleaseSafe builds: "access of union field 'int' while field 'text' is active". With |*n| in a switch prong you get a pointer to the payload and can modify it in place.

You can also ask which variant is active with std.meta.activeTag(v) and compare it to a tag, or test it with v == .nothing for tags without payloads.

Explicit tag types

When you already have an enum, reuse it:

ZIG
const Kind = enum { circle, square };
const Shape = union(Kind) {
    circle: f32,   // radius
    square: f32,   // side
};

Why this beats flags and null

Compare a C-style design (struct { int kind; double number; char *text; }) with a tagged union. In the C version nothing stops you from reading text when kind says number, and every new kind must be remembered in every if chain. The union keeps the tag and payload together, the compiler checks the switch is complete, and memory is shared so the size is that of the largest variant plus the tag.

Enum or union?

Enum One name from a fixed list. No data
Tagged union One of several shapes, each with its own data
switch Exhaustive, captures the payload safely

Together they model states, commands, tokens and results.

1 / 2

Stand-ins you can run

Rust enums with data are exactly Zig's tagged unions, and match is the exhaustive switch.

Rust Stand-in (Rust): tagged union with exhaustive match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

C builds the same thing by hand with a tag and a union, which shows what Zig automates:

C Stand-in (C): a manual tagged union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which builtin gives the name of an enum value as a string?

    @tagName(value) returns the field name; @intFromEnum returns the number.
  2. 2. What does union(enum) do?

    A tagged union remembers which field is active, so it can be switched on safely.
  3. 3. How do you read the payload of a tagged union safely?

    A switch checks the tag and gives you the payload for that variant.
  4. 4. What happens when you read v.int while the active field is text?

    The wrong-field access is detected at runtime in safe build modes.
  5. 5. Why should you avoid else when switching on an enum?

    Listing every variant makes the compiler flag all switches when the enum grows.

Summary

  • An enum is a closed list of names; use @tagName, @intFromEnum, enum(u16) for backing types and _ for open sets.
  • Enums can have methods and are parsed from text with std.meta.stringToEnum.
  • A tagged union(enum) stores one of several payloads plus the active tag.
  • switch on a union captures the payload (|v|, or |*v| for a pointer) and must be exhaustive.
  • Prefer tagged unions to flag-plus-fields designs.

Next: Optionals