Zig has type function which can be used to implement generic types when it takes a type
parameter.
For example
pub fn Generic(T: type) type {
}
This is clear to me and nothing new here. The type passed can be seen as instantiating an actual type, and it would probably end up being the type of a member field. Most of the languages I have used has same idea.
What is confusing to me now is when the parameter to the type function is anytype
which means a value can be passed to it instead of type. ie
pub fn Generic(T: anytype) type {
_ = T;
}
pub fn main() !void {
const Generic42 = Generic(42);
std.destd.debug.print("{any}", .{Generic42});
}
Now this is the part that I have not wrapped my head around. Why would one want to pass in a value this way (similar to how a type can be passed).
When Generic
accepts type
I can reason about this. Mainly that this is providing a way to fill in the concrete type ie we have a generic data structure.
But I cannot reason about when Generic
accepts a value this way. What patterns/problem is this useful for?