Hi all, I am trying to generate fields on a struct at comptime. Ideally, I’d like to be able to do something like this to generate a Vec3.
const Vec3f32 = Vec({ "x", "y", "z" }, f32);
I was able to generate something like this using a strange syntax I found here in the Zig standard library.
pub fn Vec(comptime T: type) type {
const fields = [_]std.builtin.Type.StructField{
.{ .name = "x", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
.{ .name = "y", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
.{ .name = "z", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
.{ .name = "w", .type = T, .default_value = null, .is_comptime = false, .alignment = 0 },
};
return @Type(.{ .Struct = .{
.layout = .auto,
.fields = fields[0..],
.decls = &.{},
.is_tuple = false,
}});
}
However, I’m not sure how to add functions to the struct using this syntax. How would I write a Vec
function like this that would generate full structs like the one below, given a set of field names and a number type?
const Vec3f32 = struct {
x: f32,
y: f32,
z: f32,
pub fn add(self: Vec3f32, other: Vec3f32) Vec3f32 {
return Vec3f32{ .x = self.x + other.x, .y = self.y + other.y, .z = self.z + other.z };
}
pub fn dot(self: Vec3f32, other: Vec3f32) f32 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
};
// More Vec functions...
Thanks in advance!