Re:When to use generics
by paskozdilar on Wednesday April 13, 2022 @03:55AM
(#31012186)
> But - there are some things about Go generics that are particularly weird. The biggest one is that, in a lot of cases, they can actually just be another way to write runtime polymorphism, not static polymorphism as in languages like C++.
Isn't static polymorphism the whole point of generics? Runtime polymorphism was already possible through interfaces and type switches.
Also you can't type switch a generic variable, so runtime polymorphism with generics seems literally impossible.
I wouldn't say it's the whole point but very important one. For simple types the current Go implementation does produce monomorphic functions but for others, for example interfaces and other pointer types, it does pass around a dict with metadata in runtime.
Check out this excellent blog post: https://planetscale.com/blog/generics-can-make-your-go-code-....
As far as I understand it is still compile time checked, hence it is a form of static polymorphism. The fact it is still runtime dispatched it is just an implementation choice.
I think you’re right. It’s just not exactly what many people coming from other languages expect from generics.
It’s seems like a static polymorphism but not monomorphism, which also is implemented in Go generics but for simple types.
Actually historically most generic implementations do not monomorphize either except as an optimisation: Java, C# (at least for complex types), most functional languages use some sort of type erasure. C++ and, I think, ADA were the exceptions, although it has proven more popular with newer languages.
But - there are some things about Go generics that are particularly weird. The biggest one is that, in a lot of cases, they can actually just be another way to write runtime polymorphism, not static polymorphism as in languages like C++ (https://planetscale.com/blog/generics-can-make-your-go-code-...).