Runtime equivalent of @unionInit

in my use-case, i’m receiving a data-packet which internally contains a “serialized” version of a tagged union – with the tag itself represented as a u8 and the corresponding value following…

how would i implement a runtime equivalent of @unionInit with the following signature???

fn unionInit(U: type, tag: u8, val: anytype): U

Well, you could just turn the runtime tag into a comptime value using inline switch cases:

switch(tag) {
    inline else => |comptime_tag| {
        // the tag is comptime known in here.
    },
}

The question would just be how to handle val. You have to check first if it’s the correct type, before you can do the assignment. Otherwise you end up with a compiler error.
Not accounting for type coercions (how to check if a type can be coerced into another type) you could just do it like this:

if(std.meta.FieldType(U, comptime_tag) == @TypeOf(val)) {
    return @unionInit(U, @tagName(comptime_), val);
}
2 Likes