typestar

Tagged unions in Zig

One reading, two shapes: a float when the sensor works, a reason when it does not.

const std = @import("std");

// A tagged union holds one variant and remembers which one.
const Reading = union(enum) {
    ok: f32,
    fault: []const u8,
};

fn report(r: Reading) void {
    switch (r) {
        .ok => |temp| std.debug.print("steady at {d:.1} C\n", .{temp}),
        .fault => |why| std.debug.print("sensor down: {s}\n", .{why}),
    }
}

pub fn main() void {
    report(.{ .ok = 21.5 });
    report(.{ .fault = "loose wire" });
}

How it works

  1. union(enum) stores one active variant and remembers which.
  2. switch with captures pulls out the payload of whichever variant is live.
  3. .{ .ok = 21.5 } builds a variant with anonymous struct syntax.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
409
Tokens
128
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 118 seconds.

Type this snippet

Step 3 of 3 in Structs & enums, step 15 of 27 in Language basics.

← Previous Next →