3 ms·
This is very exciting! One challenge with introducing generics after the language has shipped is that the language was already designed around their absence. I
by munificent 8y ago
This is very exciting!
One challenge with introducing generics after the language has shipped is that the language was already designed around their absence. In particular, there are a number of "generic" or "polymorphic" that are built into the language. In order to handle them specially, they often have special-purpose syntax. Examples (note: I'm not very familiar with Go, so I might have some of this wrong):
* Addition, which is overloaded for various number types, uses "+".
* Accessing array and map elements uses "[...]".
* Equality, which is overloaded for various types, uses "==".
Having dedicated syntax for these makes sense in Go 1 because they are special. They do things user code cannot do. Prohibiting operator overloading reinforces this. If you see a "+" in code, you know it's the magical built-in "+" operator.
But with generics (and potentially overloading), these operations no longer need special powers. It's possible to write your own collection type with a type-parametric "subscript operator". You just don't get to use the "[...]" syntax.
This is particularly problematic because it interacts poorly with contracts, which specify syntactically which operations are used. Most of the contract examples in the doc here use "==", "+", and "[...]".
So even though you have generics and constraints (contracts), it's very hard to define a generic function that works with both built-in generic types (slice, map, etc.) and user-defined ones.
The end result is probably going to be something similar to Java where the "best practice" is to use named methods for all operations ("Add()", "Equal()", etc.) and then provide wrappers that lift the built-in types into this more flexible world like you do with ArrayList instead of raw arrays in Java.
That sucks because the built-in syntax is better. It's inane that Java has array literals, a nice subscript operator, and a terse ".length" property but 99% of Java code doesn't get to use any of them when working with "arrays". Instead of:
array[0] = array[array.length - 1];
It's all:
array.set(0, array.get(array.size() - 1));
I could certainly be wrong, but it seems Go is on that same path.
Aside from this, the generics proposal looks really neat to me. The limitations on methods will also likely be very painful, but it's a hard problem with no easy solution given Go's approach to structural typing, methods, and the desire to not require runtime specialization. Language design is hard. Language evolution is 10x harder.