Hacker News new | ask | show | jobs
by thayne 21 days ago
> you would need to have effectively two generics implementations, one working at runtime and one working at compile time

My understanding is that go already has a hybrid system works at compiletime and sometimes at runtime.

2 comments

I'm not sure what you mean. Perhaps you are referring to the reflect package? In that case, yes, that exists. But it is limited in its power (for example, it doesn't allow to create types with methods – precisely because of the difficulties we are talking about) and a comparatively frequent source of bugs. If anything, it provides pretty strong evidence for the problems with this approach.
https://go.dev/doc/faq#generics_implementation

My point is for interface generics it could just always use a single instantiation. Similar to what java does.

Or alternatively, go could go the other direction and add a new type of interface that is only for use in generic constraints, and then generic methods could be part of that interface, but not normal interfaces, so that the generic methods could be called from other generic functions. That would be similar to rust and c++.

When I said "you need a runtime implementation of generics" I did not mean "you need dynamic dispatch". I meant "you need a type-checker and at least limited code generator at runtime".

> Similar to what java does.

Yes, if you completely forego the static implementation, you can deal with just one. Then all code is slow.

Java can get away with it, because it has a JIT compiler – so it isn't subject to the same "no runtime code generation" design restriction Go is. That also means, it can run on fewer platforms than Go.

> add a new type of interface that is only for use in generic constraints

Yes, that would be feasible. It has been ruled out, because we really don't want to have interfaces that can not be used as types. They currently exist, but the goal is to remove that restriction, not to add more of the same.

I'll note that either way, at that point we are firmly outside the realm of this particular thread. It's no longer what I was responding to.

Sorta, but it's important for the calling convention that the compiler is consistent on what is done at compiletime vs runtime. Because methods are "normal functions" for the calling convention (and can be assigned to function-typed variables), there would be a lot of gymnastics required for the compiler to make runtime-generated variants of methods work.