union

union

A bare union defines a set of possible types that a value can be as a list of fields. Only one field can be active at a time. The in-memory representation of bare unions is not guaranteed. Bare unions cannot be used to reinterpret memory. For that, use @ptrCast, or use an extern union or a packed union which have guaranteed in-memory layout. Accessing the non-active field is safety-checked Undefined Behavior:

test.zig

const Payload = union {
    int: i64,
    float: f64,
    boolean: bool,
};
test "simple union" {
    var payload = Payload{ .int = 1234 };
    payload.float = 12.34;
}
``` ```
$ zig test test.zig
Test [1/1] test "simple union"...
thread 11537 panic: access of inactive union field
/home/andy/Downloads/zig/docgen_tmp/test.zig:8:12: 0x20677b in test "simple union" (test)
    payload.float = 12.34;
           ^
/home/andy/Downloads/zig/lib/std/special/test_runner.zig:76:28: 0x22d05a in std.special.main (test)
        } else test_fn.func();
                           ^
/home/andy/Downloads/zig/lib/std/start.zig:471:37: 0x2255ba in std.start.callMain (test)
            const result = root.main() catch |err| {
                                    ^
/home/andy/Downloads/zig/lib/std/start.zig:413:12: 0x20943e in std.start.callMainWithArgs (test)
    return @call(.{ .modifier = .always_inline }, callMain, .{});
           ^
/home/andy/Downloads/zig/lib/std/start.zig:332:17: 0x208466 in std.start.posixCallMainAndExit (test)
    std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp }));
                ^
/home/andy/Downloads/zig/lib/std/start.zig:245:5: 0x208272 in std.start._start (test)
    @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
    ^
error: the following test command crashed:
docgen_tmp/zig-cache/o/333a8741816702dafd0ff99af380ebb1/test /home/andy/Downloads/zig/build-release/zig

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" {
    var payload = Payload{ .int = 1234 };
    try expect(payload.int == 1234);
    payload = Payload{ .float = 12.34 };
    try expect(payload.float == 12.34);
}
``` ```
$ zig test test.zig
Test [1/1] test "simple union"...

All 1 tests passed.

In order to use switch with a union, it must be a Tagged union.

To initialize a union when the tag is a comptime-known name, see @unionInit.

Tagged union

Unions can be declared with an enum tag type. This turns the union into a tagged union, which makes it eligible to use with switch expressions. Tagged unions coerce to their tag type: Type Coercion: unions and enums.

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 "switch on tagged union" {
    const c = ComplexType{ .ok = 42 };
    try expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);

    switch (c) {
        ComplexTypeTag.ok => |value| try expect(value == 42),
        ComplexTypeTag.not_ok => unreachable,
    }
}

test "get tag type" {
    try expect(std.meta.Tag(ComplexType) == ComplexTypeTag);
}

test "coerce to enum" {
    const c1 = ComplexType{ .ok = 42 };
    const c2 = ComplexType.not_ok;

    try expect(c1 == .ok);
    try expect(c2 == .not_ok);
}
``` ```
$ zig test test.zig
Test [1/3] test "switch on tagged union"...
Test [2/3] test "get tag type"...
Test [3/3] test "coerce to enum"...

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 };
    try expect(@as(ComplexTypeTag, c) == ComplexTypeTag.ok);

    switch (c) {
        ComplexTypeTag.ok => |*value| value.* += 1,
        ComplexTypeTag.not_ok => unreachable,
    }

    try expect(c.ok == 43);
}
``` ```
$ zig test test.zig
Test [1/1] test "modify tagged union in switch"...

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

const std = @import("std");
const expect = std.testing.expect;

const Variant = union(enum) {
    int: i32,
    boolean: bool,

    // void can be omitted when inferring enum tag type.
    none,

    fn truthy(self: Variant) bool {
        return switch (self) {
            Variant.int => |x_int| x_int != 0,
            Variant.boolean => |x_bool| x_bool,
            Variant.none => false,
        };
    }
};

test "union method" {
    var v1 = Variant{ .int = 1 };
    var v2 = Variant{ .boolean = false };

    try expect(v1.truthy());
    try expect(!v2.truthy());
}
``` ```
$ zig test test.zig
Test [1/1] test "union method"...

All 1 tests passed.

@tagName can be used to return a comptime []const u8 value representing the field name:

test.zig

const std = @import("std");
const expect = std.testing.expect;

const Small2 = union(enum) {
    a: i32,
    b: bool,
    c: u8,
};
test "@tagName" {
    try expect(std.mem.eql(u8, @tagName(Small2.a), "a"));
}
``` ```
$ zig test test.zig
Test [1/1] test "@tagName"...

All 1 tests passed.

extern union

An extern union has memory layout guaranteed to be compatible with the target C ABI.

See also:

  • extern struct

packed union

A packed union has well-defined in-memory layout and is eligible to be in a packed struct.

Anonymous Union Literals

Anonymous Struct Literals syntax can be used to initialize unions without specifying the type:

anon_union.zig

const std = @import("std");
const expect = std.testing.expect;

const Number = union {
    int: i32,
    float: f64,
};

test "anonymous union literal syntax" {
    var i: Number = .{.int = 42};
    var f = makeNumber();
    try expect(i.int == 42);
    try expect(f.float == 12.34);
}

fn makeNumber() Number {
    return .{.float = 12.34};
}
``` ```
$ zig test anon_union.zig
Test [1/1] test "anonymous union literal syntax"...

All 1 tests passed.