I'm having the following function in my personal library:
pub fn FieldType(comptime T: type, comptime field: []const u8) type {
return @TypeOf(@field(@as(T, undefined), field));
}
which can be used as
const S = struct { i: i32 };
pub fn main() void {
const F = FieldType(S, "i");
_ = F;
}
Now I want the same for pointers (so e.g. the const attribute is properly propagated):
pub fn FieldPtrType(comptime Ptr: type, comptime field: []const u8) type {
return @TypeOf(&@field(@as(Ptr, undefined), field));
}
which would be used as
const S = struct { i: i32 };
pub fn main() void {
const P1 = FieldPtrType(*S, "i"); // expect P1 == *i32
const P2 = FieldPtrType(*const S, "i"); // expect P2 == *const i32
_ = P1;
_ = P2;
}
This however fails to compile
src/root.zig:6:21: error: use of undefined value here causes undefined behavior
return @TypeOf(&@field(@as(Ptr, undefined), field));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/root.zig:13:28: note: called from here
const P1 = FieldPtrType(*S, "i"); // expect P1 == *i32
~~~~~~~~~~~~^~~~~~~~~
- Is this limitation necessary? (I see no point for undefined behavior here)
- Is there a simple workaround, or do I have to go the full route of parsing and copying the
@typeInfo()?