Function fields [src]
Prototype
pub fn fields(comptime T: type) switch (@typeInfo(T)) { .@"struct" => []const Type.StructField, .@"union" => []const Type.UnionField, .@"enum" => []const Type.EnumField, .error_set => []const Type.Error, else => @compileError("Expected struct, union, error set or enum type, found '" ++ @typeName(T) ++ "'"), }
Example
test fields {
const E1 = enum {
A,
};
const E2 = error{A};
const S1 = struct {
a: u8,
};
const U1 = union {
a: u8,
};
const e1f = comptime fields(E1);
const e2f = comptime fields(E2);
const sf = comptime fields(S1);
const uf = comptime fields(U1);
try testing.expect(e1f.len == 1);
try testing.expect(e2f.len == 1);
try testing.expect(sf.len == 1);
try testing.expect(uf.len == 1);
try testing.expect(mem.eql(u8, e1f[0].name, "A"));
try testing.expect(mem.eql(u8, e2f[0].name, "A"));
try testing.expect(mem.eql(u8, sf[0].name, "a"));
try testing.expect(mem.eql(u8, uf[0].name, "a"));
try testing.expect(comptime sf[0].type == u8);
try testing.expect(comptime uf[0].type == u8);
}
Source
pub fn fields(comptime T: type) switch (@typeInfo(T)) {
.@"struct" => []const Type.StructField,
.@"union" => []const Type.UnionField,
.@"enum" => []const Type.EnumField,
.error_set => []const Type.Error,
else => @compileError("Expected struct, union, error set or enum type, found '" ++ @typeName(T) ++ "'"),
} {
return switch (@typeInfo(T)) {
.@"struct" => |info| info.fields,
.@"union" => |info| info.fields,
.@"enum" => |info| info.fields,
.error_set => |errors| errors.?, // must be non global error set
else => @compileError("Expected struct, union, error set or enum type, found '" ++ @typeName(T) ++ "'"),
};
}