TExcelTAD
Home › Zig › Zig Tagged Unions

Zig Tagged Unions

A union is a type that holds one of several possible fields at a time. A tagged union also remembers which field is active, using an enum tag. Tagged unions let you model "this value is either a circle with a radius, or a rectangle with a width and a height" — and the compiler makes sure you handle every case when you read it.

Defining a tagged union

Write union(enum) to get a tagged union with an automatically created tag enum:

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

const Shape = union(enum) {
    circle: f64, // radius
    rectangle: struct { w: f64, h: f64 },
    triangle: struct { base: f64, height: f64 },

    fn area(self: Shape) f64 {
        return switch (self) {
            .circle => |r| std.math.pi * r * r,
            .rectangle => |rect| rect.w * rect.h,
            .triangle => |t| t.base * t.height / 2,
        };
    }
};

pub fn main() void {
    const shapes = [_]Shape{
        .{ .circle = 1.0 },
        .{ .rectangle = .{ .w = 3, .h = 4 } },
        .{ .triangle = .{ .base = 6, .height = 5 } },
    };
    for (shapes) |s| {
        std.debug.print("{t:<10} area {d:.2}\n", .{ s, s.area() });
    }
}
circle     area 3.14
rectangle  area 12.00
triangle   area 15.00

Each variant is created with exactly one field set: .{ .circle = 1.0 }. The switch captures the payload of the active variant with |r|, |rect| and so on. As with enums, the switch must cover every variant.

Why not a struct?

A struct with all the fields would waste memory and allow nonsense states (a circle with a width?). A union stores only the largest variant plus a small tag:

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

const Value = union(enum) {
    int: i64,
    float: f64,
    boolean: bool,
};

pub fn main() void {
    std.debug.print("union: {d} bytes\n", .{@sizeOf(Value)});
    std.debug.print("one i64: {d} bytes\n", .{@sizeOf(i64)});

    const v = Value{ .float = 2.5 };
    std.debug.print("active tag: {t}\n", .{v});
    std.debug.print("is float? {}\n", .{v == .float});
}
union: 16 bytes
one i64: 8 bytes
active tag: float
is float? true

A tagged union compares equal to an enum literal when that variant is active, so v == .float is a quick check.

Accessing the wrong field

You can read a field directly (v.float), but if a different variant is active, a safe build panics with access of union field 'int' while field 'float' is active. Prefer switch or an if check, which can never get it wrong.

Changing the active variant

Assign a whole new value to switch variants. To modify the payload in place, capture a pointer with |*p|:

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

const Token = union(enum) {
    number: i32,
    word: []const u8,
    end,

    fn show(self: Token) void {
        switch (self) {
            .number => |n| std.debug.print("number({d}) ", .{n}),
            .word => |w| std.debug.print("word({s}) ", .{w}),
            .end => std.debug.print("end\n", .{}),
        }
    }
};

pub fn main() void {
    var tokens = [_]Token{ .{ .number = 4 }, .{ .word = "apples" }, .{ .number = 10 }, .end };

    // double every number in place
    for (&tokens) |*t| {
        switch (t.*) {
            .number => |*n| n.* *= 2,
            else => {},
        }
    }
    for (tokens) |t| t.show();

    tokens[1] = .{ .number = 0 }; // replace the variant entirely
    tokens[1].show();
    std.debug.print("\n", .{});
}
number(8) word(apples) number(20) end
number(0) 

Notice end has no type: a variant without a payload is written as just its name (its payload type is void).

A tiny expression evaluator

Tagged unions shine for tree-shaped data, such as the syntax tree of a calculator:

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

const Expr = union(enum) {
    num: f64,
    add: [2]*const Expr,
    mul: [2]*const Expr,
    neg: *const Expr,

    fn eval(self: Expr) f64 {
        return switch (self) {
            .num => |n| n,
            .add => |p| p[0].eval() + p[1].eval(),
            .mul => |p| p[0].eval() * p[1].eval(),
            .neg => |e| -e.eval(),
        };
    }
};

pub fn main() void {
    // (2 + 3) * -4
    const two = Expr{ .num = 2 };
    const three = Expr{ .num = 3 };
    const four = Expr{ .num = 4 };
    const sum = Expr{ .add = .{ &two, &three } };
    const minus_four = Expr{ .neg = &four };
    const product = Expr{ .mul = .{ &sum, &minus_four } };
    std.debug.print("result = {d}\n", .{product.eval()});
}
result = -20

Untagged unions

A plain union (without (enum)) has no tag. It is smaller but you must track the active field yourself; it is mainly used for C interop (extern union) and low-level tricks. Prefer union(enum).

Kind Remembers active field Use
union(enum) yes everyday modelling of alternatives
union(MyEnum) yes, using your own enum when the tag enum is reused elsewhere
union no (safety-checked in Debug) low-level code
extern union no C compatibility

Test yourself

How many fields of a tagged union hold a value at the same time?

  1. All of them
  2. Exactly one
  3. Zero or more
  4. Two

In switch (shape) { .circle => |r| … }, what is r?

  1. The tag
  2. The payload of the circle variant
  3. A pointer to the switch
  4. The union size

What happens when you read v.int while v.float is active in a Debug build?

  1. You get the bits reinterpreted
  2. 0
  3. A panic: access of inactive union field
  4. A compile error always