#Tagged Unions Idioms

1 messages · Page 1 of 1 (latest)

storm zodiac
#

Hey all,
I am currently on a quest to learn idiomatic* Zig and I am doing so by building a tiny compiler.

When using tagged unions, I find myself using std.meta.activeTag a lot.

For example,

const std = @import("std");

pub const Type = enum {
    number,
    boolean,
};

pub const Value = union(Type) {
    number: f32,
    boolean: bool,

    pub fn equals(self: Value, other: Value) bool {
        if (std.meta.activeTag(self) != std.meta.activeTag(other)) return false;

        return switch (self) {
            .number => |n| n == other.number,
            .boolean => |b| b == other.boolean,
        };
    }
};

Is this expected? Are there patterns that would allow me not to?
Reaching for meta that often makes me feel like I am doing something wrong, but maybe it's entirely expected.


*: I have been playing with the language for a while, I am really trying to understand how Zig "ought to be written", more than "what's possible", if that makes any sense.

fallen sky
#

at the very least you only need to call activeTag on one of the operands, unions coerce to their tag.
that is what activeTag is doing, you could expand it to @as(Type, val) == other.

#

btw you dont need to declare the tag enum seperately, you could union(enum) to infer a tag from the union, which you could extract with some reflection, there is probably a std.meta function for that anyway.