Proper way to cast comptime data to `anyopaque`

Hi @ExpandingMan welcome to Ziggit!

You can assign your var to a const and then use that const in the return value instead. That way the return value doesn’t directly refer to a comptime var anymore and is seen as static data that doesn’t refer back to comptime.
For a full explanation read this:

So I think this should work:

fn buildfield(comptime name: [:0]const u8, comptime typ: type, comptime opts: anytype) Type.StructField {
    comptime var default_value: ?*const anyopaque = null;
    comptime var is_comptime: bool = false;
    comptime var alignment: comptime_int = @alignOf(typ);
    inline for (meta.fields(@TypeOf(opts))) |opt| {
        if (mem.eql(u8, opt.name, "default_value")) {
            default_value = @ptrCast(&@field(opts, opt.name));
        } else if (mem.eql(u8, opt.name, "is_comptime")) {
            is_comptime = @field(opts, opt.name);
        } else if (mem.eql(u8, opt.name, "alignment")) {
            alignment = @field(opts, opt.name);
        } else {
            @compileError("got bogus argument for buildfield option");
        }
    }
    const frozen_default_value = default_value;
    const frozen_is_comptime = is_comptime;
    const frozen_alignment = alignment;
    return Type.StructField{
        .name = name,
        .type = typ,
        .default_value = frozen_default_value,
        .is_comptime = frozen_is_comptime,
        .alignment = frozen_alignment,
    };
}
3 Likes