3 ms·
> you can think about generics as a better kind of interfaces No, you can't, because generics don't provide the key feature of interfaces: run-time dynamism.
by brandonbloom 9y ago
> you can think about generics as a better kind of interfaces
No, you can't, because generics don't provide the key feature of interfaces: run-time dynamism.
You could make a case that static polymorphism and dynamic polymorphism could be accomplished by a single mechanism, as traits do in Rust, but you can't say generics are "better" than interfaces, since they solve a different set of problems, with different implementation strategies, despite related theoretical foundations.
> The problem of not having generics is that the community can't build its own implementation of useful data structures
This is not true either, although it is true that it is harder to do this sort of thing in Go, the result may in fact not be as fast as you can achieve with monomorphisation, and you may have to write more code by hand.
The "trick" is the Go model is to provide an interface (which yes, potentially unnecessarily uses a dynamic mechanism) to implement indirect operations. For example the Swap function of https://golang.org/pkg/sort/#Interface https://golang.org/pkg/sort/#Interface enables https://golang.org/pkg/container/heap/#Interface https://golang.org/pkg/container/heap/#Interface - which is a reusable data structure. Compiler-level static-generics for slices and arrays, combined with indirecting through array indexes, enables you to avoid boxing when instantiating the heap interface. The data structure can be instantiated with an interface once, so there is no dynamic lookup for heap operations, but there is still a double indirect call.
Yes, this is less convenient than proper generics, but this doesn't mean you can't do these things.
Furthermore, I've never actually needed to do this outside of sorting (which is, absolutely, is annoying) in large projects. Almost every time I need a specialized data structure, I usually need it for performance reasons, and so hand-specializing for my needs tends to be worthwhile anyway.
> Generics are rarely useful in your own code, but they allow people to create good abstractions in their libraries.
I'd like to see something like templates or generics for Go, but I definitely don't want Java-style "fake" generics without code specialization. Furthermore, I found that the vast majority of generics-heavy libraries back in my C# days were more trouble than they are worth, despite meaningful opportunities for better performance with value types. Copy/paste almost always resulted in a better outcome.
- shaan7 9y ago> Yes, this is less convenient than proper generics, but this doesn't mean you can't do these things. Yep, assembly is less convenient than Go, but it doesn't mean you can't write programs using assembly.