Skip to content

Commit 8094fa5

Browse files
mluggVexu
authored andcommitted
std: add meta.FieldType
This is simply a small convenience wrapper around 'meta.fieldInfo(T, .field).type'. However, this operation is common enough that it makes sense to have its own function for.
1 parent 5bd69c6 commit 8094fa5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

lib/std/meta.zig

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,32 @@ test "std.meta.fieldInfo" {
556556
try testing.expect(comptime uf.type == u8);
557557
}
558558

559+
pub fn FieldType(comptime T: type, comptime field: FieldEnum(T)) type {
560+
if (@typeInfo(T) != .Struct and @typeInfo(T) != .Union) {
561+
@compileError("Expected struct or union, found '" ++ @typeName(T) ++ "'");
562+
}
563+
564+
return fieldInfo(T, field).type;
565+
}
566+
567+
test "std.meta.FieldType" {
568+
const S = struct {
569+
a: u8,
570+
b: u16,
571+
};
572+
573+
const U = union {
574+
c: u32,
575+
d: *const u8,
576+
};
577+
578+
try testing.expect(FieldType(S, .a) == u8);
579+
try testing.expect(FieldType(S, .b) == u16);
580+
581+
try testing.expect(FieldType(U, .c) == u32);
582+
try testing.expect(FieldType(U, .d) == *const u8);
583+
}
584+
559585
pub fn fieldNames(comptime T: type) *const [fields(T).len][]const u8 {
560586
comptime {
561587
const fieldInfos = fields(T);

0 commit comments

Comments
 (0)