I searched for generic function in the docs and didn't find it
There are a few clues to how it would be done, such as the declarations of built in functions. However, there isn't a good description of how this should be done like there is for generic data structures, and some of the semantics are unclear. In particular:
- What is the
vartype, and what are its semantics? (it is in many declarations, but I can't find any documentation about it) - Does zig use duck typing? Or do I need to specify constraints somehow to use operators or members of a type
- Are there any best practices for defining generic functions?
- Can you define generic functions the same way you do with structs, by returning an anonymous function pointer?
- Can you use a function (ex. @typeof) to compute the return type or parameter type of a function?
Types in Zig have the type type and can be used as values just like any other. Through this you can write a function that takes in a type and returns a new type based on the input. When people say "generic" they are usually referring to a specific permutation of this where the output is somewhat agnostic to the input type ie std.ArrayList which will change the inner type based on the generic input but will give you a list structure regardless of the input type.
-
varhas been renamed toanytypeand used to allow a function parameter to accept many different but congruent types. Similar to interfaces in other languages but slightly harder on the language server. - yes
- there's a couple things to watch out for that can affect binary size that would be great in an article
- yes. generic functions are the same as normal functions. though syntactically its easier at the moment to return a struct and then call the inner function at the callsite
- yes