Zig 0.16.0 struct creation makes weird error

    fn flagsType(flags: []const Flag) type {
        var names: [1 + flags.len][]const u8 = undefined;
        var types: [1 + flags.len]type = undefined;
        var atts: [1 + flags.len]std.builtin.Type.StructField.Attributes = undefined;

        names[0], types[0], atts[0] = .{ "raw_text", []const []const u8, .{} };
        for (names[1..], types[1..], atts[1..], flags) |*_name, *t, *att, flag| {
            _name.*, t.*, att.* = .{
                flag.name(),
                if (flag.type) |_t| ?_t.type else bool,
                .{ .default_value_ptr = &(if (flag.type) |_| null else false) },
            };
        }

        return @Struct(.auto, null, &names, &types, &atts);
    }

Creates the compiler warning

src/Command.zig:284:53: error: comptime dereference requires '?[]u8' to have a well-defined layout
        return @Struct(.auto, null, &names, &types, &atts);
                                                    ^~~~~

Version is Zig 0.16.0

PS: there is no tag for 0.16.0 yet

1 Like

You need to explicitly coerce the null default value to an optional of the field’s type:
.{ .default_value_ptr = &(if (flag.type) |_t| @as(?_t.type, null) else false) },
This is likely weirdness relating to the type of default_value_ptr being ?*const anyopaque.

2 Likes

Now that you say it I literally did it this way previously and just forgot why I did it, thought it was 0.16.0 related but it makes a ton of sense.

Thank you!

yes, the error is weird, but It’s because the default value ptr was the wrong type.