authorgravatar for mlugg@mlugg.co.ukMatthew Lugg <mlugg@mlugg.co.uk> 2022-12-21 12:00:55+00:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-01-03 12:47:48+02:00
log8094fa5d48c48fe7b6993e1577209811de7a0e9b
tree0f665ed7f970d346fb97f9dfd3123751dbb08c73
parent5bd69c655d9e04102c8a64ced1215c9d69f4f03f

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 files changed, 26 insertions(+), 0 deletions(-)

lib/std/meta.zig+26
......@@ -556,6 +556,32 @@ test "std.meta.fieldInfo" {
556556 try testing.expect(comptime uf.type == u8);
557557}
558558
559pub 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
567test "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
559585pub fn fieldNames(comptime T: type) *const [fields(T).len][]const u8 {
560586 comptime {
561587 const fieldInfos = fields(T);