test.zig
$ zig test test.zig
1/1 test "simple union"... access of inactive union field
/home/andy/Downloads/zig/docgen_tmp/test.zig:8:12: 0x2059db in test "simple union" (test)
payload.float = 12.34;
^
/home/andy/Downloads/zig/lib/std/special/test_runner.zig:61:28: 0x22d9d1 in std.special.main (test)
} else test_fn.func();
^
/home/andy/Downloads/zig/lib/std/start.zig:334:37: 0x2072dd in std.start.posixCallMainAndExit (test)
const result = root.main() catch |err| {
^
/home/andy/Downloads/zig/lib/std/start.zig:162:5: 0x207012 in std.start._start (test)
@call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
^
error: the following test command crashed:
docgen_tmp/zig-cache/o/2e7f715609483f0cd9100db66b70c1a0/test
You can activate another field by assigning the entire union:
test.zig
const std = @import("std");
const expect = std.testing.expect;
const Payload = union {
int: i64,
float: f64,
boolean: bool,
};
test "simple union" {
expect(payload.int == 1234);
payload = Payload{ .float = 12.34 };
}
$ zig test test.zig
1/1 test "simple union"... OK
All 1 tests passed.
In order to use switch with a union, it must be a .
To initialize a union when the tag is a comptime-known name, see .
test.zig
$ zig test test.zig
1/3 test "switch on tagged union"... OK
2/3 test "@TagType"... OK
3/3 test "coerce to enum"... OK
All 3 tests passed.
In order to modify the payload of a tagged union in a switch expression, place a *
before the variable name to make it a pointer:
test.zig
const std = @import("std");
const expect = std.testing.expect;
const ComplexTypeTag = enum {
ok,
not_ok,
};
const ComplexType = union(ComplexTypeTag) {
ok: u8,
not_ok: void,
};
test "modify tagged union in switch" {
var c = ComplexType{ .ok = 42 };
expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);
switch (c) {
}
expect(c.ok == 43);
}
$ zig test test.zig
1/1 test "modify tagged union in switch"... OK
All 1 tests passed.
Unions can be made to infer the enum tag type. Further, unions can have methods just like structs and enums.
test.zig
$ zig test test.zig
1/1 test "union method"... OK
All 1 tests passed.
test.zig
const std = @import("std");
const expect = std.testing.expect;
const Small2 = union(enum) {
a: i32,
b: bool,
c: u8,
};
test "@tagName" {
expect(std.mem.eql(u8, @tagName(Small2.a), "a"));
}
$ zig test test.zig
1/1 test "@tagName"... OK
All 1 tests passed.
An extern union
has memory layout guaranteed to be compatible with the target C ABI.
See also:
A packed union
has well-defined in-memory layout and is eligible to be in a .
Anonymous Struct Literals syntax can be used to initialize unions without specifying the type:
$ zig test anon_union.zig
All 1 tests passed.