union

    test.zig

    1. $ zig test test.zig
    2. Test 1/1 simple union...access of inactive union field
    3. /home/andy/dev/zig/docgen_tmp/test.zig:8:12: 0x20410f in ??? (test)
    4. payload.Float = 12.34;
    5. ^
    6. /home/andy/dev/zig/build/lib/zig/std/special/test_runner.zig:13:25: 0x225bdb in ??? (test)
    7. if (test_fn.func()) |_| {
    8. ^
    9. /home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:122:22: 0x225366 in ??? (test)
    10. root.main() catch |err| {
    11. ^
    12. /home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:43:5: 0x2250d1 in ??? (test)
    13. @noInlineCall(posixCallMainAndExit);
    14. ^
    15. Tests failed. Use the following command to reproduce the failure:
    16. /home/andy/dev/zig/docgen_tmp/test

    You can activate another field by assigning the entire union:

    test.zig

    1. const std = @import("std");
    2. const assert = std.debug.assert;
    3. const Payload = union {
    4. Int: i64,
    5. Float: f64,
    6. Bool: bool,
    7. test "simple union" {
    8. var payload = Payload{ .Int = 1234 };
    9. payload = Payload{ .Float = 12.34 };
    10. assert(payload.Float == 12.34);
    11. }
    1. $ zig test test.zig
    2. Test 1/1 simple union...OK
    3. All tests passed.

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

    test.zig

    1. $ zig test test.zig
    2. Test 1/2 switch on tagged union...OK
    3. Test 2/2 @TagType...OK
    4. All 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

    1. const std = @import("std");
    2. const assert = std.debug.assert;
    3. const ComplexTypeTag = enum {
    4. Ok,
    5. NotOk,
    6. };
    7. const ComplexType = union(ComplexTypeTag) {
    8. Ok: u8,
    9. NotOk: void,
    10. };
    11. test "modify tagged union in switch" {
    12. var c = ComplexType{ .Ok = 42 };
    13. ComplexTypeTag.Ok => |*value| value.* += 1,
    14. ComplexTypeTag.NotOk => unreachable,
    15. }
    16. assert(c.Ok == 43);
    17. }
    1. $ zig test test.zig
    2. Test 1/1 modify tagged union in switch...OK
    3. All tests passed.

    Unions can be made to infer the enum tag type. Further, unions can have methods just like structs and enums.

    1. $ zig test test.zig
    2. Test 1/1 union method...OK
    3. All tests passed.

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

    test.zig

    1. const std = @import("std");
    2. const assert = std.debug.assert;
    3. const Small2 = union(enum) {
    4. A: i32,
    5. B: bool,
    6. C: u8,
    7. };
    8. test "@tagName" {
    9. assert(std.mem.eql(u8, @tagName(Small2.C), "C"));
    10. }
    1. $ zig test test.zig
    2. Test 1/1 @tagName...OK

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

    See also: