Re:Maintain It with Zig
by woodrowbarlow on Wednesday September 08, 2021 @02:48PM
(#28461424)
i love that zig doesn't have a special syntax for generics, it just allows anything to be resolved at compile-time -- including types. which gives you generics 'for free'.
[ Parent
| on HN ]
I've only cursory of Zig, so bear with me. Does this mean that Zig templates are like C++, that is, duck typing? Or is there a notion of constraining the type arguments?
Re:Maintain It with Zig
by kristoff_it on Wednesday September 08, 2021 @05:07PM
(#28463082)
It's duck typed but it's not based on a funky and limited syntax, but rather types at comptime become normal arguments to functions that you can then inspect using normal Zig code.
I wrote a blog post about comptime if you want to learn more: https://kristoff.it/blog/what-is-zig-comptime/
It's duck typed but let's say your "template" takes an integer and divides by two depending on some boolean (perhaps you need to return a lookup table of sometimes half the bitwidth of an integer type). That function called by your template at compile time to maybe-divide-by-two is in the same language as runtime zig, and you could even conceivably call that very same function as a compiled entity in the runtime context.