Zig Unions
A struct holds all of its fields at once. Sometimes you want the opposite: a value that’s one of several things. A setting might be a number, or a yes/no flag, or a piece of text, but never all three at the same time. A union is a type like that: it lists several fields, and only one of them holds a value at any moment. This page covers the plain, “bare” union. It’s short, because the honest advice at the end is that you’ll mostly use its safer sibling, the tagged union, in the next lesson. But knowing how bare unions work, and how they go wrong, makes the tagged version click.
A first union
Section titled “A first union”A union looks like a struct, with union instead of struct:
const std = @import("std");
const Setting = union { number: i64, flag: bool, text: []const u8,};
pub fn main() void { const volume: Setting = .{ .number = 80 }; const dark_mode: Setting = .{ .flag = true }; const theme: Setting = .{ .text = "ocean" };
std.debug.print("volume: {d}\n", .{volume.number}); std.debug.print("dark mode: {}\n", .{dark_mode.flag}); std.debug.print("theme: {s}\n", .{theme.text});}Output:
volume: 80dark mode: truetheme: oceanAll three values have the same type, Setting, but each one holds a different kind of data. You create a union with exactly one field set: .{ .number = 80 }. That field is the active field. Setting two at once, like .{ .number = 1, .flag = true }, doesn’t build.
C programmers know this idea already. Python and JavaScript don’t have it, because a variable there can hold anything anyway. In Zig, every value has one fixed type, and a union is how you say “this type can carry one of these kinds of data”.
Why bother? Size
Section titled “Why bother? Size”A union only needs room for its biggest field, because only one is stored at a time. A struct with the same fields needs room for all of them:
const std = @import("std");
const AsStruct = struct { number: i64, ratio: f64, flag: bool,};
const AsUnion = union { number: i64, ratio: f64, flag: bool,};
pub fn main() void { std.debug.print("struct: {d} bytes\n", .{@sizeOf(AsStruct)}); std.debug.print("union: {d} bytes\n", .{@sizeOf(AsUnion)});}Output:
struct: 24 bytesunion: 16 bytesThe biggest field is 8 bytes, but this union is 16. That’s because zig run makes a debug build, and in debug (and safe) builds Zig secretly stores which field is active, so it can catch mistakes. In a fast or small build, the same program prints union: 8 bytes on this machine (64-bit Linux), and that hidden check is gone. Hold on to that thought, it matters in a moment. Build modes are covered in Zig Build Modes.
Only one field is active
Section titled “Only one field is active”You can read the active field as often as you like. To switch to a different field, assign a whole new union value:
const std = @import("std");
const Setting = union { number: i64, flag: bool,};
pub fn main() void { var s: Setting = .{ .number = 3 }; std.debug.print("number: {d}\n", .{s.number});
s.number += 1; std.debug.print("number: {d}\n", .{s.number});
s = .{ .flag = false }; std.debug.print("flag: {}\n", .{s.flag});}Output:
number: 3number: 4flag: falseChanging the active field in place (s.number += 1) is fine. Moving to another field takes s = .{ .flag = false }. Writing s.flag = false while number is active is the same mistake as reading the wrong field, which is next.
Reading the wrong field
Section titled “Reading the wrong field”What happens if you read a field that isn’t active? In a debug build, Zig notices, thanks to that hidden extra data, and stops the program:
const std = @import("std");
const Setting = union { number: i64, ratio: f64,};
pub fn main() void { var s: Setting = .{ .number = 42 }; _ = &s; std.debug.print("as ratio: {e}\n", .{s.ratio});}You’ll see something like:
thread 21252 panic: access of union field 'ratio' while field 'number' is activemain.zig:11:43: 0x11e3def in main (main.zig) std.debug.print("as ratio: {e}\n", .{s.ratio}); ^That’s a clear message pointing at the right line. Now the catch: in a fast build (-O fast), that check isn’t there. The same program ran here and printed as ratio: 2.08e-322, which is the bytes of the number 42 read as if they were a float. No error, just a wrong value. This is illegal behavior: Zig doesn’t promise anything about what happens, and you can’t rely on it, which is a nice way of saying “a bug that might hide”. The reference lists it as wrong union field access.
The real problem: who knows which field is active?
Section titled “The real problem: who knows which field is active?”The union itself doesn’t tell you which field is set, at least not in a way your code can ask. So any code that receives a union has to “just know”. You can’t even switch on it:
const std = @import("std");
const Setting = union { number: i64, flag: bool,};
fn show(s: Setting) void { switch (s) { .number => |n| std.debug.print("{d}\n", .{n}), .flag => |f| std.debug.print("{}\n", .{f}), }}
pub fn main() void { show(.{ .number = 5 });}main.zig:9:13: error: switch on union with no attached enum switch (s) { ^main.zig:3:17: note: consider 'union(enum)' hereconst Setting = union { ^~~~~The compiler even tells you the answer. One way to fix it by hand is to keep a separate enum next to the union, saying which field is active:
const std = @import("std");
const Kind = enum { number, flag };
const Setting = struct { kind: Kind, value: union { number: i64, flag: bool, },};
fn show(s: Setting) void { switch (s.kind) { .number => std.debug.print("number {d}\n", .{s.value.number}), .flag => std.debug.print("flag {}\n", .{s.value.flag}), }}
pub fn main() void { show(.{ .kind = .number, .value = .{ .number = 5 } }); show(.{ .kind = .flag, .value = .{ .flag = true } });}Output:
number 5flag trueIt works, but look at how much can go wrong. Nothing stops you from writing .kind = .flag with .value = .{ .number = 5 }. Every new field means updating the enum, the union and every switch, and keeping them in sync is up to you. This “enum plus union” pair is such a common pattern that Zig builds it into the language. That’s the tagged union.
Tagged unions: the preview
Section titled “Tagged unions: the preview”Write union(enum) instead of union, and Zig keeps the enum for you, always in sync:
const std = @import("std");
const Setting = union(enum) { number: i64, flag: bool,};
fn show(s: Setting) void { switch (s) { .number => |n| std.debug.print("number {d}\n", .{n}), .flag => |f| std.debug.print("flag {}\n", .{f}), }}
pub fn main() void { show(.{ .number = 5 }); show(.{ .flag = true });}Output:
number 5flag trueThe switch now works, the payload comes out as |n|, and you can’t mix up the kind and the value, because they’re one thing. That’s the whole next lesson, Zig Tagged Unions.
So when is a bare union the right choice?
Section titled “So when is a bare union the right choice?”Not often, and that’s fine. It makes sense when:
- Something else already tells you the active field. For example, an array of unions where a separate list, or the position, says what each item is, and you want to save the extra tag in every item.
- You talk to C. C unions have no tag. For that, Zig has
extern union, which uses C’s memory layout. There’s alsopacked unionfor bit-level work; see Zig Packed & Extern Structs.
For everything else, reach for union(enum). The extra few bytes buy you a switch that checks every case, and a program that can never read the wrong field without a clear panic.
Practice
Section titled “Practice”1. A shape size
Section titled “1. A shape size”Make a bare union Size with a side: f64 (for a square) and a radius: f64 (for a circle). Create one of each and print them.
Hint: set one field when you create each value, and read back that same field.
Show solution
const std = @import("std");
const Size = union { side: f64, radius: f64,};
pub fn main() void { const square: Size = .{ .side = 4 }; const circle: Size = .{ .radius = 1.5 }; std.debug.print("square side: {d}\n", .{square.side}); std.debug.print("circle radius: {d}\n", .{circle.radius});}Output:
square side: 4circle radius: 1.5Both fields are f64, but they mean different things. Notice that nothing in circle tells your code it’s a circle: you just know, because you wrote it.
2. Which line panics?
Section titled “2. Which line panics?”Before running it, decide which line stops this program in a debug build, and why.
const std = @import("std");
const Cell = union { count: u32, label: []const u8,};
pub fn main() void { var c: Cell = .{ .count = 1 }; // line A c.count += 1; // line B c = .{ .label = "two" }; // line C std.debug.print("{d}\n", .{c.count}); // line D}Hint: after line C, which field is active?
Show solution
Line D. Lines A and B create and change the active field count. Line C replaces the whole union, so label is active. Line D reads count, which is no longer active, and you’ll see panic: access of union field 'count' while field 'label' is active.
3. Make it a tagged union
Section titled “3. Make it a tagged union”Change the union from exercise 1 into a tagged union and write a function describe(s: Size) void that prints square with side 4 or circle with radius 1.5 using a switch.
Hint: only one word changes in the type: union becomes union(enum). Then each prong gets the value with |v|.
Show solution
const std = @import("std");
const Size = union(enum) { side: f64, radius: f64,};
fn describe(s: Size) void { switch (s) { .side => |v| std.debug.print("square with side {d}\n", .{v}), .radius => |v| std.debug.print("circle with radius {d}\n", .{v}), }}
pub fn main() void { describe(.{ .side = 4 }); describe(.{ .radius = 1.5 });}Output:
square with side 4circle with radius 1.5Now describe can find out what it got, instead of having to be told. The next lesson goes much further with this.
- A union lists several fields, but only one is active at a time; you set exactly one when you create it.
- It needs room for its biggest field only (plus a hidden safety tag in
debugandsafebuilds). - To change which field is active, assign a whole new value:
s = .{ .flag = false };. - Reading or writing an inactive field is illegal behavior: a clear panic in
debugbuilds, a silent wrong value infastbuilds. - You can’t
switchon a bare union, because it doesn’t record which field is active. - Bare unions are for special cases (C interop with
extern union, tight memory). Day to day, useunion(enum).
Next up: Zig Tagged Unions, unions that remember their active field and work with switch.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: union: bare unions, activating fields and the wrong-field panic.
- Zig language reference: wrong union field access: the safety check and what it catches.
- Zig language reference: extern union: unions with C’s memory layout.
- Zig language reference: tagged union: the safer version you’ll use most.