What would you replace it with? It can be anything in this case.
I think there are cases where anytype parameters expect specific values and there it would be nice to be able to quickly identify what is accepted, but I don’t know how you would add such a syntax that still would be ziggy.
For example go uses some kind of Type-Variable constraint language for types,
but adding such a thing to Zig seems to me like giving up on finding a solution that matches the Zig spirit.
Currently you need to read the code, personally I think that is better than having an inaccurate replication of the code in the form of prose in cases where it would be hard to describe, however in this case it would be good if the documentation said something like “context is an arbitrary value provided as first argument to the comparison function”, the reason why it currently isn’t is probably because this is obvious and can be seen from the code, once you are familiar with this type of code and because the standard library is still written to serve the construction of the compiler and didn’t have its rewrite for more user friendly-ness.
Part of me would like to have a feature to be able to use “Type Checking” functions as parameter types instead of anytype
, that would be invoked with a type and accept or reject it, however proposals along those lines have been rejected, as far as I can tell mostly because they would lead the language towards a tendency to create towers of abstractions like c++ tends to do, creating increasing complexity that has marginal value when compared to using simple assertions instead. Those constructs also tend to be just a declarative copy of what you already can do with assertions, thus they would be against the idea of “Only one obvious way to do things.”
When writing generic functions that use anytype
it is simple to write comptime checkMyTypeCheck(@TypeOf(my_param));
as the first line of that function and such a function can provide a detailed error message for what was expected.
I am not totally on one side or the other, but so far I haven’t seen a proposal that actually fits Zig, but I also haven’t researched that deep.
Some issues related to this are:
I think reading these types of issues and what they discuss and link to, can give you more of a grasp of what has been proposed already, why certain solutions get rejected and possibly what areas / solutions could be researched.
But from what I have seen it seems like a very complex topic and difficult to find something that fits Zig and is an improvement over status quo, without just copying a feature from some other language.
Ideally somebody would find some slight addition/change to the language that sets of a series of small changes that leads to a different way of writing these generic functions without having to introduce huge new features, but still allows things like good documentation / integration with zls.