diff options
| author | mlugg <mlugg@mlugg.co.uk> | 2022-12-21 12:00:55 +0000 |
|---|---|---|
| committer | Veikka Tuominen <git@vexu.eu> | 2023-01-03 12:47:48 +0200 |
| commit | 8094fa5d48c48fe7b6993e1577209811de7a0e9b (patch) | |
| tree | 0f665ed7f970d346fb97f9dfd3123751dbb08c73 /lib/std/meta.zig | |
| parent | 5bd69c655d9e04102c8a64ced1215c9d69f4f03f (diff) | |
| download | zig-8094fa5d48c48fe7b6993e1577209811de7a0e9b.tar.gz zig-8094fa5d48c48fe7b6993e1577209811de7a0e9b.zip | |
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.
Diffstat (limited to 'lib/std/meta.zig')
| -rw-r--r-- | lib/std/meta.zig | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/std/meta.zig b/lib/std/meta.zig index db284f8b61..e97edf1718 100644 --- a/lib/std/meta.zig +++ b/lib/std/meta.zig @@ -556,6 +556,32 @@ test "std.meta.fieldInfo" { try testing.expect(comptime uf.type == u8); } +pub fn FieldType(comptime T: type, comptime field: FieldEnum(T)) type { + if (@typeInfo(T) != .Struct and @typeInfo(T) != .Union) { + @compileError("Expected struct or union, found '" ++ @typeName(T) ++ "'"); + } + + return fieldInfo(T, field).type; +} + +test "std.meta.FieldType" { + const S = struct { + a: u8, + b: u16, + }; + + const U = union { + c: u32, + d: *const u8, + }; + + try testing.expect(FieldType(S, .a) == u8); + try testing.expect(FieldType(S, .b) == u16); + + try testing.expect(FieldType(U, .c) == u32); + try testing.expect(FieldType(U, .d) == *const u8); +} + pub fn fieldNames(comptime T: type) *const [fields(T).len][]const u8 { comptime { const fieldInfos = fields(T); |
