I am currently experimenting with types in Zig and I came across something that I couldnt make sence of.
The Zig way of doing generics is something like this:
pub const Bra(T: type) type {
return sturct { ... };
}
And I worked a bit with this ziguanic way of doing it and I like it very much. But after a while I was curious for a deeper understanding and I also had the problem what to do when I want a type to be dependent on 2 input variables and I played around and came up with this:
fn F(T: type, comptime i: usize) type {
return struct {
const Self = @This();
const a: usize = i;
const b: usize = 1337;
fn init() Self {
return Self{};
}
fn g(self: Self) usize {
_ = self;
return a;
}
fn bra(self: Self, o: Self, t: T) void {
std.debug.print("self: {} other: {} , {}\n", .{ self.g(), o.g(), t });
}
};
}
At the beginning I thought that maybe the type of this would depend on the const elements inside the struct (because you always see this const Self = @This();
), but after some print type information I was proven wrong.
pub fn main() void {
const f1 = f(u32, 1);
const f2 = f(u32, 2);
const l1 = f1.init();
const l2 = f2.init();
l1.a(l2, 10)
}
After I tried this I got this compiler error:
src/main.zig:31:12: error: expected type 'main.F(u32,1)', found 'main.F(u32,2)'
l1.bra(l2, 10);
^~
src/main.zig:5:12: note: struct declared here (2 times)
return struct {
^~~~~~
src/main.zig:19:31: note: parameter type declared here
fn bra(self: Self, o: Self, t: T) void
So currently my assumption is that a type depends on the function call? Is there another way to declare a type? Did I miss something?
Thanks for your help!
Side questions: Is a struct {}
of type type
?