Skip to content
LumenaryAcademy
Foundations 60 min

Structs, enums and tagged unions

Grouping data with structs and methods, naming choices with enums, and modelling "one of several kinds" safely with tagged unions.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Data with a shape

Real programs model things: a vector with two coordinates, a bank account with an owner and a balance, a day of the week, a shape that may be a circle or a rectangle, an input event that may be a key press, a mouse click or a request to quit. Zig gives you three tools for this, and they cover nearly everything.

A struct groups named fields, and can carry functions (methods) and constants with it. An enum names a fixed set of choices. A tagged union holds exactly one of several kinds of value, together with a tag saying which, and the compiler makes sure you handle every kind. There are no classes, no inheritance and no constructors that run implicitly. That sounds austere, but tagged unions plus exhaustive switch replace much of what class hierarchies are used for in other languages, more safely.

DefinitionsH

Definitions

Definition— struct

const Vec2 = struct { x: f64, y: f64 }; defines a type with named fields. A struct is a value: assignment copies it. Its body can also contain declarations: constants, functions and nested types. Every Zig source file is itself a struct, which is why @import("std") returns something you access with dots.

Definition— struct literal and result type

.{ .x = 3, .y = 4 } creates a struct value; the leading dot means "of the type expected here", taken from the variable's declared type or the function parameter. Fields with default values (balance_cents: i64 = 0) may be left out. A decl literal such as .zero or .init(...) refers to a declaration of the expected type, so var v: Vec2 = .zero; means Vec2.zero.

Definition— method

A function declared inside a struct (or enum or union) whose first parameter is that type or a pointer to it. v.length() is shorthand for Vec2.length(v), and when the first parameter is a pointer, v.scale(2) passes &v automatically. There is nothing else special about methods: no this, no hidden dispatch.

Definition— enum

A type whose values are a fixed set of names: enum { monday, tuesday, ... }. Each value has an integer tag; enum(u16) { ok = 200, ... } chooses the tag type and values. @intFromEnum, @enumFromInt and @tagName convert to and from integers and names.

Definition— tagged union

union(enum) { circle: f64, rectangle: Rect, quit } holds exactly one of its fields at a time plus an enum tag recording which. switch on a tagged union must handle every tag, and |payload| captures the active field's value. A tag may have no payload (quit), and reading a field that is not active is illegal behaviour, checked in safe modes.

ComputationC

Structs and methods

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

const Vec2 = struct {
    x: f64,
    y: f64,

    // A declaration inside the struct: usable as the "decl literal" .zero.
    pub const zero: Vec2 = .{ .x = 0, .y = 0 };

    pub fn add(a: Vec2, b: Vec2) Vec2 {
        return .{ .x = a.x + b.x, .y = a.y + b.y };
    }

    pub fn length(v: Vec2) f64 {
        return @sqrt(v.x * v.x + v.y * v.y);
    }

    // Takes a pointer, so it can change the vector it is called on.
    pub fn scale(v: *Vec2, factor: f64) void {
        v.x *= factor;
        v.y *= factor;
    }
};

const Account = struct {
    owner: []const u8,
    balance_cents: i64 = 0, // default field value
    history: [8]i64 = @splat(0),
    count: usize = 0,

    pub fn init(owner: []const u8) Account {
        return .{ .owner = owner };
    }

    pub fn deposit(self: *Account, cents: i64) void {
        self.balance_cents += cents;
        self.history[self.count] = cents;
        self.count += 1;
    }

    pub fn transactions(self: *const Account) []const i64 {
        return self.history[0..self.count];
    }
};

pub fn main() void {
    var v: Vec2 = .{ .x = 3, .y = 4 };
    std.debug.print("length {d}\n", .{v.length()}); // same as Vec2.length(v)
    v.scale(2); // Zig passes &v automatically
    const w = v.add(.{ .x = 1, .y = 1 });
    std.debug.print("v=({d}, {d}) w=({d}, {d})\n", .{ v.x, v.y, w.x, w.y });

    var origin: Vec2 = .zero; // decl literal
    origin = origin.add(w);
    std.debug.print("origin moved to ({d}, {d})\n", .{ origin.x, origin.y });

    var acct: Account = .init("Wanjiru");
    acct.deposit(5000);
    acct.deposit(-1250);
    std.debug.print("{s}: {d} cents after {any}\n", .{ acct.owner, acct.balance_cents, acct.transactions() });
    std.debug.print("@sizeOf(Vec2) = {d} bytes\n", .{@sizeOf(Vec2)});
}
text
length 5
v=(6, 8) w=(7, 9)
origin moved to (7, 9)
Wanjiru: 3750 cents after { 5000, -1250 }
@sizeOf(Vec2) = 16 bytes

length and add take the vector by value: they read it and return something new. scale takes *Vec2 because it changes the vector it is called on; the call v.scale(2) passes &v for you, which only works because v is a var. On a const vector, calling scale is a compile error, so the receiver type documents and enforces whether a method can modify.

Passing a struct by value looks expensive but usually is not. Zig may pass a large by-value parameter by reference under the hood, since the function cannot modify it anyway; you choose by meaning (does the function change the caller's value?) rather than by size. Note that transactions takes *const Account because it returns a slice into the account's own history array. If it took the account by value, the slice would point into a copy that disappears when the function returns: the dangling-slice bug from the previous lesson, in disguise.

Note

Because every file is a struct, a file can be a type. A file named Account.zig that declares the fields owner: []const u8, and balance_cents: i64 = 0, at the top level, followed by its methods, is imported with const Account = @import("Account.zig"); and used like any struct; inside it, @This() names the type. By convention, files that are types get capitalised names, and files that are namespaces of functions get lower-case names.

Account.init("Wanjiru") is an ordinary function returning a struct, the conventional name for "make one of these". Zig has no constructors, so init is just a naming convention, and .init(...) uses it as a decl literal. You will see .init and .empty constantly in the standard library: var list: std.ArrayList(u8) = .empty;.

Worked examplesH

Enums

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

const Weekday = enum {
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday,

    pub fn isWeekend(d: Weekday) bool {
        return switch (d) {
            .saturday, .sunday => true,
            else => false,
        };
    }

    pub fn next(d: Weekday) Weekday {
        const n = (@backingInt(d) + 1) % 7;
        return @fromBackingInt(@intCast(n));
    }
};

// An enum with an explicit integer type and chosen values.
const Status = enum(u16) {
    ok = 200,
    not_found = 404,
    teapot = 418,
    server_error = 500,
};

pub fn main() void {
    const today: Weekday = .friday;
    std.debug.print("{t} weekend? {}\n", .{ today, today.isWeekend() });
    std.debug.print("then {t}, then {t}\n", .{ today.next(), today.next().next() });
    std.debug.print("sunday wraps to {t}\n", .{Weekday.sunday.next()});

    const s: Status = .not_found;
    std.debug.print("{t} = {d}\n", .{ s, @backingInt(s) });

    // From a name (for example, read from a config file) to an enum value.
    if (std.meta.stringToEnum(Weekday, "tuesday")) |d| {
        std.debug.print("parsed {t}, index {d}\n", .{ d, @backingInt(d) });
    }
    std.debug.print("unknown name gives {?}\n", .{std.meta.stringToEnum(Weekday, "funday")});

    // Iterate over every value of an enum.
    var weekend_days: u32 = 0;
    for (std.enums.values(Weekday)) |d| {
        if (d.isWeekend()) weekend_days += 1;
    }
    std.debug.print("{d} weekend days\n", .{weekend_days});
}
text
friday weekend? false
then saturday, then sunday
sunday wraps to monday
not_found = 404
parsed tuesday, index 1
unknown name gives null
2 weekend days

An enum's methods live inside it, just like a struct's. isWeekend uses switch with several values in one prong, and next converts to the integer tag and back. The format specifier {t} prints an enum's tag name. std.meta.stringToEnum turns a name read from text into an enum value, returning null for an unknown name, and std.enums.values gives every value so you can loop over them.

Status shows an enum with a chosen integer type and values, typical for protocol codes and file formats. Where other systems might add values later, mark the enum non-exhaustive with a final _ field (enum(u16) { ok = 200, not_found = 404, _ }); then any u16 can be converted to it, and a switch must include an _ or else prong for unknown values.

Worked examplesH

Tagged unions

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

const Shape = union(enum) {
    circle: f64, // radius
    rectangle: struct { w: f64, h: f64 },
    triangle: struct { a: f64, b: f64, c: f64 }, // side lengths

    pub fn area(self: Shape) f64 {
        return switch (self) {
            .circle => |r| std.math.pi * r * r,
            .rectangle => |r| r.w * r.h,
            .triangle => |t| blk: {
                const s = (t.a + t.b + t.c) / 2; // Heron's formula
                break :blk @sqrt(s * (s - t.a) * (s - t.b) * (s - t.c));
            },
        };
    }
};

const Event = union(enum) {
    key: u8,
    click: struct { x: i32, y: i32 },
    resize: struct { w: u32, h: u32 },
    quit, // a tag with no payload
};

pub fn main() void {
    const shapes = [_]Shape{
        .{ .circle = 1.0 },
        .{ .rectangle = .{ .w = 2, .h = 3.5 } },
        .{ .triangle = .{ .a = 3, .b = 4, .c = 5 } },
    };
    var total: f64 = 0;
    for (shapes) |s| {
        std.debug.print("{t:<10} {d:>7.3}\n", .{ s, s.area() });
        total += s.area();
    }
    std.debug.print("total      {d:>7.3}\n", .{total});

    const events = [_]Event{
        .{ .key = 'q' }, .{ .click = .{ .x = 10, .y = 20 } }, .{ .resize = .{ .w = 800, .h = 600 } }, .quit,
    };
    for (events) |e| {
        switch (e) {
            .key => |k| std.debug.print("key '{c}'\n", .{k}),
            .click => |c| std.debug.print("click at {d},{d}\n", .{ c.x, c.y }),
            .resize => |r| std.debug.print("resize to {d}x{d}\n", .{ r.w, r.h }),
            .quit => std.debug.print("quit\n", .{}),
        }
    }
    // A tagged union can be compared with a tag directly.
    std.debug.print("last is quit: {}\n", .{events[3] == .quit});
}
text
circle       3.142
rectangle    7.000
triangle     6.000
total       16.142
key 'q'
click at 10,20
resize to 800x600
quit
last is quit: true

Each shape stores only the data it needs, and area handles each kind in its own prong, capturing the payload: |r| is a radius for a circle and a struct with w and h for a rectangle. The triangle prong uses a labeled block to compute Heron's formula in several steps.

The Event union is the shape of most event loops, interpreters and message protocols: a value that is one of several variants, each with its own data. Compare it with an object-oriented design, where Event would be a base class with a virtual handle method overridden by subclasses. That design makes it easy to add new kinds of event; the tagged union makes it easy to add new operations on events, and the compiler checks that every operation handles every kind. Add a scroll variant to Event and every switch without an else stops compiling until you handle it, which is exactly the help you want when a program grows.

Worked examplesH

Packed bits and tuples

Two more shapes of data round out the picture. A packed struct with a backing integer gives names to individual bits, and a tuple is an anonymous struct whose fields are numbered rather than named.

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

// Unix file permissions are 9 bits: read/write/execute for owner, group and others.
// A packed struct names each bit; fields are laid out from the least significant bit.
const Permissions = packed struct(u9) {
    other_x: bool = false,
    other_w: bool = false,
    other_r: bool = false,
    group_x: bool = false,
    group_w: bool = false,
    group_r: bool = false,
    owner_x: bool = false,
    owner_w: bool = false,
    owner_r: bool = false,
};

fn minMax(values: []const i32) struct { i32, i32 } { // returns a tuple
    var lo = values[0];
    var hi = values[0];
    for (values[1..]) |v| {
        lo = @min(lo, v);
        hi = @max(hi, v);
    }
    return .{ lo, hi };
}

pub fn main() void {
    var p: Permissions = .{ .owner_r = true, .owner_w = true, .owner_x = true, .group_r = true, .group_x = true, .other_r = true };
    const bits: u9 = @bitCast(p);
    std.debug.print("mode {o} ({b:0>9}), size {d} byte(s)\n", .{ bits, bits, @sizeOf(Permissions) });

    p.other_r = false; // clear one bit by name
    const from_number: Permissions = @bitCast(@as(u9, 0o640));
    std.debug.print("now {o}; 640 means group can write? {} read? {}\n", .{ @as(u9, @bitCast(p)), from_number.group_w, from_number.group_r });

    // Tuples: anonymous structs whose fields are numbered.
    const lo, const hi = minMax(&.{ 4, -7, 19, 0 });
    const pair = .{ "answer", 42 };
    std.debug.print("lo={d} hi={d} pair[0]={s} pair[1]={d}\n", .{ lo, hi, pair[0], pair[1] });
}
text
mode 754 (111101100), size 2 byte(s)
now 750; 640 means group can write? false read? true
lo=-7 hi=19 pair[0]=answer pair[1]=42

packed struct(u9) promises that the nine bool fields occupy exactly nine bits, starting from the least significant, so @bitCast converts between the struct and a u9 without any arithmetic. Printed in octal with {o}, the bits are the familiar Unix mode 754 (owner may read, write and execute; group may read and execute; others may read). Clearing other_r by name gives 750, and decoding 0o640 shows that the group may read but not write. The size is 2 bytes because a u9 needs more than one.

minMax returns struct { i32, i32 }, a tuple type, and the caller destructures it into two constants. Tuples are handy for returning a couple of values without naming a type, and std.debug.print's argument list .{ ... } has been a tuple all along. Once the values have meanings worth naming, prefer a struct with named fields.

ExplanationH

Memory layout: auto, extern and packed

By default Zig is free to lay out a struct's fields in any order and with any padding it likes, which lets it reorder fields to save space. Two other layouts give you control when it matters:

LayoutField order and paddingUsed for
struct (auto)chosen by the compileralmost everything
extern structas written, with C's padding rulespassing data to and from C, file formats defined by C headers
packed structas written, no padding, fields packed bit by bithardware registers, network headers, flag sets

The same three fields a: u8, b: u32, c: u8 occupied 8 bytes as an ordinary struct and 12 as an extern struct when this course was tested (C's rules put three bytes of padding after a so that b is aligned, and three more after c), while a packed struct { a: u4, b: u3, c: bool } fits in a single byte. Packed structs make bit fields readable: instead of masks and shifts, you write flags.c = true, and the compiler generates the bit operations.

There is no inheritance. Code reuse comes from composition (a struct containing another), from free functions and from comptime generics, the subject of a later lesson. When you genuinely need run-time polymorphism over an open set of types, as the standard library's std.mem.Allocator and std.Io.Writer do, the pattern is a struct holding a pointer to the object and a pointer to a table of functions: the interface is written out explicitly, with no hidden machinery.

Example— An interface written out by hand

Here is the shape of a run-time interface in Zig, simplified from the pattern std.mem.Allocator uses. Any type can be a Sound if it provides a play function; the interface stores a type-erased pointer to the object and a pointer to the function:

zig
const Sound = struct {
    ptr: *anyopaque, // the object, type erased
    playFn: *const fn (ptr: *anyopaque) void, // what to call on it

    pub fn play(s: Sound) void {
        s.playFn(s.ptr);
    }
};

const Drum = struct {
    hits: u32 = 0,
    fn play(ptr: *anyopaque) void {
        const self: *Drum = @ptrCast(@alignCast(ptr));
        self.hits += 1;
    }
    pub fn sound(self: *Drum) Sound {
        return .{ .ptr = self, .playFn = play };
    }
};

A Drum, a Flute and a Bell can each hand out a Sound, and a function taking Sound plays any of them. Every piece of the mechanism, including the cast back from *anyopaque to the concrete type, is visible in the source. Zig code reaches for this only when the set of types is open-ended; when it is closed and known, a tagged union is simpler and lets the compiler check every case.

Common misconceptionsH

Common misconceptions

Misconception

"self is a keyword." It is an ordinary parameter name chosen by convention. pub fn length(v: Vec2) f64 works the same as pub fn length(self: Vec2) f64. What matters is the type of the first parameter: value, *T or *const T.

Misconception

"I can make a field private." Zig has no private fields: any code that can see a struct can read and write all of its fields. pub applies only to declarations (functions, constants, nested types). Invariants are protected by convention and documentation, for example a doc comment saying "do not modify directly; use deposit", and the standard library relies on exactly that.

Misconception

"An untagged union is the same as a tagged one." A plain union has no tag, so nothing records which field is active; switching on it is impossible, and safety checks are limited. Use union(enum), which costs only the few bytes of the tag, unless you are matching a C layout (extern union) or squeezing memory in a way you have measured.

Misconception

"Field order in my struct is the order in memory." Only for extern and packed structs. Never write code that depends on the layout of an auto struct, such as casting its bytes to a file format; use extern struct or serialise the fields one by one.

Misconception

"I should add an else to every switch to be safe." An else on a switch over an enum or tagged union turns off the exhaustiveness check that warns you when a new variant is added. Handle every case explicitly when you can, and use else only when "everything else" really is one behaviour.

Exercises

Exercises

1. Structs, enums and tagged unions

CoreComputational

What does this program print?

const std = @import("std");

const Counter = struct {
    n: u32 = 0,
    fn bumpCopy(self: Counter) u32 {
        var copy = self;
        copy.n += 10;
        return copy.n;
    }
    fn bump(self: *Counter) void {
        self.n += 1;
    }
};

pub fn main() void {
    var a: Counter = .{};
    var b = a;
    a.bump();
    b.bump();
    b.bump();
    const r = a.bumpCopy();
    std.debug.print("{d} {d} {d}\n", .{ a.n, b.n, r });
}

2. Structs, enums and tagged unions

CoreComputational

With the lesson's Weekday enum and its next method, what does this print?

var d: Weekday = .thursday;
for (0..10) |_| d = d.next();
std.debug.print("{t} {d}\n", .{ d, @intFromEnum(d) });

3. Structs, enums and tagged unions

StretchComputational

On x86-64 Linux, what is @sizeOf(E) for const E = extern struct { a: u8, b: u16, c: u8 };? (An extern struct follows C's layout rules: each field is placed at the next offset that is a multiple of its alignment, and the total size is rounded up to a multiple of the largest alignment.)

4. Structs, enums and tagged unions

CoreComputational

What does this program print?

const std = @import("std");

const Token = union(enum) {
    number: i64,
    plus,
    minus,
    word: []const u8,
};

pub fn main() void {
    const tokens = [_]Token{ .{ .number = 7 }, .plus, .{ .word = "x" }, .minus, .{ .number = 2 } };
    var total: i64 = 0;
    var sign: i64 = 1;
    for (tokens) |t| switch (t) {
        .number => |n| total += sign * n,
        .plus => sign = 1,
        .minus => sign = -1,
        .word => |w| std.debug.print("skip {s} ", .{w}),
    };
    std.debug.print("{d}\n", .{total});
}

5. Structs, enums and tagged unions

CoreHuman

A program has const Event = union(enum) { key: u8, click: Point, quit }; and twelve switch statements over events, none with an else prong. You add a variant scroll: i32. What happens?

Choose one

6. Structs, enums and tagged unions

Warm-upHuman

For a Matrix struct, which methods should take self: *Matrix (a mutable pointer)? Select all that apply.

Choose all that apply

Further reading and resources