An Alternative to `anytype` Duck-Typing

I just want to point out that more recently, the strategy followed by the standard library appears to not be to introduce superfluous “type shape” validation logic and to instead let compile errors guide the user toward figuring out what the expectations are. See for example this commit, which removed such validation logic from ArrayHashMap, and this recently merged PR which did the same for HashMap.

The issue linked by the PR also demonstrates a problem with having a separate validation function from the implicit validation from the usage site: it’s easy for the two to grow subtly out of sync and for the validation function to be more strict than it actually needs to be.

Most problems with anytype can be classified as “tooling issues”, either in the form of bad/confusing/insufficient compile errors, or insufficient information provided by tools like autodoc or ZLS.

I can’t find the exact issue it was discussed in, but for compile errors I know there have been talks about making sure module boundaries are taken into account when omitting error traces, so that even if an error occurs deep inside std.fmt it should still highlight the first usage outside of the std module instead of requiring -freference-trace to start seeing traces from user code. This would probably help a lot of users more easily make sense of compile errors and fix their code.

For tools like autodoc or ZLS, I’m not going to be as bold as to say that fixing it would be trivial, but at least for simple cases it should definitely be possible to analyze how an anytype parameter is used inside a function, by looking at expressions like duck.speak("quack"); or const x: usize = duck.num_feathers;, and then provide hints to the caller like “duck should expose a quack method that takes a *const [5:0]u8 and returns void” or “duck should have a num_feathers field of a type coercible to usize”.

7 Likes