Skip to content

Zig Tagged Unions

A tagged union is a value that’s one of several kinds, where each kind can carry its own data. A shape is a circle with a radius, or a rectangle with a width and height. A key press carries a key, a mouse click carries a position, and “quit” carries nothing. If you know Rust, this is Zig’s version of Rust’s enum with data. In TypeScript you’d build it as a discriminated union. In Python you’d probably use a few classes and isinstance. In Zig it’s union(enum), and together with switch it’s one of the tools you’ll reach for most.

You saw the idea at the end of Zig Unions: write union(enum) instead of union. Each field is one kind, and its type is the data that kind carries:

const std = @import("std");
const Shape = union(enum) {
circle: f64,
rect: struct { w: f64, h: f64 },
dot,
};
pub fn main() void {
const a: Shape = .{ .circle = 2.5 };
const b: Shape = .{ .rect = .{ .w = 3, .h = 4 } };
const c: Shape = .dot;
std.debug.print("{any}\n", .{a});
std.debug.print("{any}\n", .{b});
std.debug.print("{any}\n", .{c});
}

Output:

.{ .circle = 2.5 }
.{ .rect = .{ .w = 3, .h = 4 } }
.{ .dot = void }

Three things to notice:

  • .{ .circle = 2.5 } creates a circle and stores 2.5 as its data, called the payload.
  • rect’s payload is a small struct written right there in the field type. That’s normal and handy.
  • dot has no type at all. Its payload is void, meaning “nothing”, and you create it with just .dot.

Behind the scenes, Zig creates an enum with one tag per field (circle, rect, dot) and stores it next to the payload. That stored tag is what makes the union “tagged”: the value always knows which kind it is.

To use a tagged union, you switch on it. Each prong can capture the payload with |name|:

const std = @import("std");
const Shape = union(enum) {
circle: f64,
rect: struct { w: f64, h: f64 },
dot,
};
fn area(shape: Shape) f64 {
return switch (shape) {
.circle => |r| std.math.pi * r * r,
.rect => |size| size.w * size.h,
.dot => 0,
};
}
pub fn main() void {
const shapes = [_]Shape{
.{ .circle = 1 },
.{ .rect = .{ .w = 3, .h = 4 } },
.dot,
};
for (shapes) |shape| {
std.debug.print("{t}: {d:.2}\n", .{ shape, area(shape) });
}
}

Output:

circle: 3.14
rect: 12.00
dot: 0.00

In the .circle prong, r is the f64 radius. In the .rect prong, size is the struct with w and h. Each capture has the right type for its kind, so there’s no way to grab the radius of a rectangle by mistake. {t} prints the kind’s name.

Just like with enums, the switch has to cover every kind. Add a triangle to Shape later, and every switch that forgot it becomes a compile error. In Rust you’d call this exhaustive pattern matching. The language reference on tagged unions has the official examples.

Like structs and enums, a tagged union can hold functions. The area function above fits nicely inside Shape:

const std = @import("std");
const Shape = union(enum) {
circle: f64,
square: f64,
pub fn area(self: Shape) f64 {
return switch (self) {
.circle => |r| std.math.pi * r * r,
.square => |side| side * side,
};
}
pub fn scaled(self: Shape, factor: f64) Shape {
return switch (self) {
.circle => |r| .{ .circle = r * factor },
.square => |side| .{ .square = side * factor },
};
}
};
pub fn main() void {
const s: Shape = .{ .square = 2 };
const big = s.scaled(3);
std.debug.print("{d} -> {d}\n", .{ s.area(), big.area() });
}

Output:

4 -> 36

scaled returns a Shape, so each prong builds the new value with a plain .{ ... }.

Sometimes you only care about one kind. You can compare a tagged union with a tag directly:

const std = @import("std");
const Message = union(enum) {
text: []const u8,
ping,
quit,
};
pub fn main() void {
const inbox = [_]Message{ .{ .text = "hi" }, .ping, .{ .text = "bye" }, .quit };
var texts: u32 = 0;
for (inbox) |msg| {
if (msg == .text) texts += 1;
if (msg == .quit) break;
}
std.debug.print("{d} text messages\n", .{texts});
const first = inbox[0];
if (first == .text) {
std.debug.print("first says: {s}\n", .{first.text});
}
}

Output:

2 text messages
first says: hi

msg == .text compares only the tag, not the payload. Once you’ve checked, you can read the payload as a field: first.text. That’s safe here because of the if. Read the wrong field (say, first.text on a ping), and you get the same panic as with bare unions, access of union field 'text' while field 'ping' is active. When you need the payload, a switch (or a check right before) is the safest habit.

A normal capture is a read-only copy. To change the payload inside the union, capture a pointer with |*name|:

const std = @import("std");
const Account = union(enum) {
active: u32,
frozen,
};
pub fn main() void {
var acc: Account = .{ .active = 100 };
switch (acc) {
.active => |*balance| balance.* += 50,
.frozen => {},
}
std.debug.print("{any}\n", .{acc});
}

Output:

.{ .active = 150 }

balance is a pointer to the number stored inside acc, and balance.* is that number, so += 50 changes acc itself. acc has to be a var for this. Forget the * and write |balance| balance += 50, and you get error: cannot assign to constant, because a plain capture can’t be changed.

Two more ways to change a tagged union:

  • If you know the kind, assign through the field: acc.active += 1; (only while active is the active field).
  • To switch to another kind, assign a whole new value: acc = .frozen;.

Pointer captures shine in loops. Here every price in a list is doubled, while the other kinds are left alone:

const std = @import("std");
const Item = union(enum) {
price: u32,
free,
};
pub fn main() void {
var items = [_]Item{ .{ .price = 10 }, .free, .{ .price = 4 } };
for (&items) |*item| {
switch (item.*) {
.price => |*p| p.* *= 2,
.free => {},
}
}
for (items) |item| std.debug.print("{any}\n", .{item});
}

Output:

.{ .price = 20 }
.{ .free = void }
.{ .price = 8 }

for (&items) |*item| gives a pointer to each item in the array, switch (item.*) looks at the item itself, and |*p| points into its payload. It reads like a lot of stars at first, but each one means the same thing: “I want to change the real thing, not a copy”. Zig Pointers explains * and .* properly.

When several kinds need the same code, you have a few options. You can list them in one prong, use else, or use inline else, which runs the prong once for each remaining kind and also gives you the tag:

const std = @import("std");
const Event = union(enum) {
key: u8,
click: struct { x: i32, y: i32 },
resize: struct { w: u32, h: u32 },
quit,
};
fn log(event: Event) void {
switch (event) {
.quit => std.debug.print("bye!\n", .{}),
inline else => |payload, tag| std.debug.print("{t}: {any}\n", .{ tag, payload }),
}
}
pub fn main() void {
log(.{ .key = 'q' });
log(.{ .click = .{ .x = 10, .y = 20 } });
log(.quit);
}

Output:

key: 113
click: .{ .x = 10, .y = 20 }
bye!

The second capture, tag, is the kind as an enum value. inline else is needed here because payload has a different type for each kind (a u8, then a struct), so Zig writes out the prong once per kind while compiling. Use it for logging or debugging like this. For real logic, separate prongs are easier to read. inline is covered in Zig Inline Functions, and the {any} that prints the key as 113 instead of q is the same bytes-as-numbers habit you saw with strings.

The hidden enum is a real type you can name. std.meta.Tag(Event) gives it to you, and a tagged union turns into its tag when you ask for that type:

const std = @import("std");
const Event = union(enum) {
key: u8,
quit,
};
pub fn main() void {
const e: Event = .{ .key = 'x' };
const kind: std.meta.Tag(Event) = e;
std.debug.print("kind: {t}\n", .{kind});
std.debug.print("same as activeTag: {}\n", .{kind == std.meta.activeTag(e)});
}

Output:

kind: key
same as activeTag: true

That’s useful when you want to store or pass around just “what kind”, without the data. You can also write the enum yourself and use it as the tag, as union(Kind) where Kind is an enum with the same names. Then the tag type has a name you can use everywhere, like a parameter type.

Here’s the kind of code tagged unions are made for: a tiny calculator that runs a list of commands. Each command has different data, and the switch makes sure every one is handled:

const std = @import("std");
const Command = union(enum) {
add: i64,
multiply: i64,
reset,
print: []const u8,
};
pub fn main() void {
const program = [_]Command{
.{ .add = 5 },
.{ .multiply = 3 },
.{ .print = "after multiply" },
.reset,
.{ .add = 7 },
.{ .print = "at the end" },
};
var total: i64 = 0;
for (program) |cmd| {
switch (cmd) {
.add => |n| total += n,
.multiply => |n| total *= n,
.reset => total = 0,
.print => |label| std.debug.print("{s}: {d}\n", .{ label, total }),
}
}
}

Output:

after multiply: 15
at the end: 7

If you later add a subtract command, the compiler won’t let you forget to handle it. That’s the big win of tagged unions: the type describes every possibility, and switch makes sure you deal with each one.

Make a tagged union Payment with cash (no payload), card (the last four digits, a u16) and voucher (a code, text). Write describe(p: Payment) void that prints paid in cash, paid by card ending 4242 or paid with voucher SPRING.

Hint: cash, with no type gives a void payload. In the switch, the .cash prong doesn’t need a capture.

Show solution
const std = @import("std");
const Payment = union(enum) {
cash,
card: u16,
voucher: []const u8,
};
fn describe(p: Payment) void {
switch (p) {
.cash => std.debug.print("paid in cash\n", .{}),
.card => |last4| std.debug.print("paid by card ending {d}\n", .{last4}),
.voucher => |code| std.debug.print("paid with voucher {s}\n", .{code}),
}
}
pub fn main() void {
describe(.cash);
describe(.{ .card = 4242 });
describe(.{ .voucher = "SPRING" });
}

Output:

paid in cash
paid by card ending 4242
paid with voucher SPRING

Each prong gets exactly the data its kind carries, with the right type: a number for the card, text for the voucher.

Given a list of Shape values (circle: f64, square: f64), count how many circles there are and add up the sides of all squares.

Hint: use shape == .circle for counting, or a switch with captures for both jobs at once.

Show solution
const std = @import("std");
const Shape = union(enum) {
circle: f64,
square: f64,
};
pub fn main() void {
const shapes = [_]Shape{
.{ .circle = 1 },
.{ .square = 2 },
.{ .circle = 5 },
.{ .square = 3.5 },
};
var circles: u32 = 0;
var sides: f64 = 0;
for (shapes) |shape| {
switch (shape) {
.circle => circles += 1,
.square => |side| sides += side,
}
}
std.debug.print("{d} circles, square sides add up to {d}\n", .{ circles, sides });
}

Output:

2 circles, square sides add up to 5.5

The .circle prong doesn’t need the radius, so it has no capture at all. A capture you don’t use would be an error.

Each item in a cart is either full: u32 (a price in cents) or sale: u32 (already reduced). Take 10 off every full price, in place, and leave sale items alone. Then print the cart.

Hint: loop with for (&cart) |*item|, switch (item.*), and a pointer capture |*price|.

Show solution
const std = @import("std");
const Item = union(enum) {
full: u32,
sale: u32,
};
pub fn main() void {
var cart = [_]Item{ .{ .full = 250 }, .{ .sale = 90 }, .{ .full = 40 } };
for (&cart) |*item| {
switch (item.*) {
.full => |*price| price.* -= 10,
.sale => {},
}
}
for (cart) |item| {
switch (item) {
.full => |price| std.debug.print("full price: {d}\n", .{price}),
.sale => |price| std.debug.print("on sale: {d}\n", .{price}),
}
}
}

Output:

full price: 240
on sale: 90
full price: 30

The first loop changes the payloads through pointers, the second only reads them, so plain captures are enough there.

  • union(enum) { a: T, b: U, c } is a value that’s one of several kinds, each with its own payload; c alone has no payload.
  • Create one with .{ .a = value }, or just .c for a kind without data.
  • switch with |x| captures gets each payload with the right type, and must handle every kind.
  • value == .kind checks only the tag; then value.kind reads the payload.
  • |*x| captures a pointer, so x.* = ... changes the payload in place (the union must be a var).
  • inline else => |payload, tag| handles the remaining kinds one by one; std.meta.Tag(U) is the tag enum.
  • Tagged unions are Zig’s answer to Rust’s enums and TypeScript’s discriminated unions.

Next up: Zig Anonymous Structs & Tuples, the .{ ... } values you’ve been passing to print all along.

Quick check

1. In switch (shape) { .circle => |r| ..., ... }, what is r?
2. How do you create the quit kind of union(enum) { key: u8, quit }?
3. You want to add 1 to the payload inside a var tagged union during a switch. Which capture works?
4. What does msg == .text check for a tagged union msg?