#On struct initialization

1 messages · Page 1 of 1 (latest)

snow river
#
const Foo = struct {
    bar: u8,
    baz: u8 = 42,
};

For the struct above, if I had to initialize all fields to undefined, I would do something like:

const foo: Foo = undefined;

How can I initialize all fields without a default value to undefined besides doing:

const foo = Foo{ .bar = undefined };

For structs with a large number of fields this can get pretty verbose.

bitter lintel
#

I dont exactly know but a suggestion would be to set the default value of bar to undefined, and then Foo{} would give you what you want

#

I dont think what you want exactly exists but you could do it with some comptime magic, but thats probably not worth the trouble

bitter lintel
#
pub fn initUndefined(comptime T: type) T {
    const struct_info = @typeInfo(T).Struct;

    var ret: T = undefined;

    inline for (struct_info.fields) |field| {
        @field(ret, field.name) = if (field.default_value) |default| @as(*const field.type, @ptrCast(default)).* else undefined;
    }

    return ret;
}
#

did it out of curiosity ^^