fn StructFieldDefaultValue(comptime sf: std.builtin.Type.StructField) *const sf.type {
const fi_type_dvalue = sf.default_value.?;
const fi_type_aligned: *align(sf.alignment) const anyopaque = @alignCast(fi_type_dvalue);
return @as(*const sf.type, @ptrCast(fi_type_aligned));
}
fn CreateDefaultStruct(comptime T: type) T {
const type_info = @typeInfo(T);
if (type_info != .@"struct") {
@compileError("expected tuple or struct argument, found " ++ @typeName(T));
}
const fields_info = type_info.@"struct".fields;
var instance: T = undefined;
inline for (fields_info) |fi| {
if (fi.default_value) |_| {
@field(instance, fi.name) = StructFieldDefaultValue(fi).*;
} else {
@field(instance, fi.name) = undefined;
}
}
return instance;
}
for normal struct
types, the above example works as expected,
but for this comptime generated type(if you really want to test create a test project and paste it in the build.zig
file) I get this error:
error: cannot store runtime value in compile time variable
@field(instance, fi.name) = StructFieldDefaultValue(fi).*;
But the thing is if I replace
@field(instance, fi.name) = StructFieldDefaultValue(fi).*;
with
const dvalue_aligned: *align(fi.alignment) const anyopaque = @alignCast(dvalue);
const value = @as(*const fi.type, @ptrCast(dvalue_aligned)).*;
@field(instance, fi.name) = value;
It(value
) somehow becomes comptime value? Why?