When can the tag_type field be null?

what it says in the title. I have only once had this type field be null and I cannot reproduce it.

https://ziglang.org/documentation/master/std/#std.builtin.Type.Union

Wouldn’t it be null for an untagged union?

///test.zig
const std = @import("std");

const tag = enum {
    empty,
    not_empty,
};

const plain = union {
    empty: void,
    not_empty: u8,
};

const tagged = union(tag) {
    empty: void,
    not_empty: u8,
};

pub fn main() void {
    std.debug.print("{any} vs {any}\n", .{
        @typeInfo(plain).@"union".tag_type,
        @typeInfo(tagged).@"union".tag_type,
    });
}

Prints null vs test.tag in my environment (0.14.0-dev.2293, WSL2).

3 Likes

Interesting, thank you. I didnt know that it was possible to declare a union like that. I tried earlier but thought it didnt work because I didnt provide the void type for my empty equivalent.

It’s a “classical” form of tagged union, with explicit enum.

Also you can use

const tagged = union(enum) {
    empty: void,
    not_empty: u8,
};

shortcut, in which case that enum will be inferred automatically.