Output:
Found Default initialized field: a = undefined
Found Default initialized field: b = 22
Found Default initialized field: c = undefined
Found Default initialized field: optional = undefined
But I’m using a very weird type: UndefinedComparisonType
Is there another way to do it?
No, there is no other way to do it, since undefined cannot be compared at compile time (→causing a compiler error). Also be aware that the way you are doing it, may be patched in the future, so I’d recommend not to rely on it too heavily.
What you can do however, is getting rid of the redundant @as(*const anyopaque. Doing it twice won’t change a thing.
I have a lot of structs that I want to reflect to an scripting system and I wanted to know which ones will be in an undefined state if I default initialize them in the script system.
I had something like this (But if T has fields defaulted to undefined will not trigger a compiler error) and If I can’t detect it at comptime…
So I will do the opposite. What dimdin proposes, never use undefined for struct fields default initializations. And then in that function check if they have a default value or not.
I know that this function will not compile if a type T, can’t be default initialize by T{}.
But I want to crash only if the function is used at runtime not at compile time so I ended up with this:
const default_initialize_fn_generated = struct {
fn defaultInitialize(ptr: *T) void {
var new_T: T = undefined;
inline for (@typeInfo(T).@"struct".fields) |field| {
if (comptime field.defaultValue()) |default_field_value| {
@field(new_T, field.name) = default_field_value;
} else {
ds.fatalm("{s} can't be default initialized.", .{@typeName(T)}, @src());
}
}
ptr.* = new_T;
}
}.defaultInitialize;
Is there a way to know if an struct type can be default initialized without checking all the fields?
I miss read the code as operating an instance of the struct in which case the values in the fields defaulted to undefined, would be, well undefined, outside of debug and release safe.
I did as well at first, which is why I translated it to test form. I still think this is a dodgy idea in most cases, possibly including OP’s, but I remain very impressed with the power of Zig’s comptime introspection of types.