top | item 39289297

(no title)

Zach_the_Lizard | 2 years ago

Part of the issue is that Go has a variety of design choices / limitations that conspire to produce different design patterns in this area than what you might see with e.g. Java.

For example: let's say we want to implement something akin to Java's Comparator interface.

Java allows interfaces to be extended with default implementations. It also allows methods to specify their own generics separate from the entire interface / class.

Thus the "comparing()" method can take in a Function<T, U> that extracts a value of type U from T that is used for comparison purposes. The return type is Comparator<T>.

(Generics simplified a bit, there are other overloads, etc.)

There's also thenComparing(), which allows chaining Comparator instances and / or chaining Function<T, U>.

As a consequence, one can use .thenComparing() to build up a Comparator from the fields on a class pretty quickly. Especially with lambda syntax.

Go doesn't support methods having different type parameters than the overall interface / struct.

Go also doesn't have default implementations. It doesn't allow function or method overloading.

Go does have first class functions, however.

To build the equivalent capability, you'd most likely build everything around a comparison function (func[T any](a, b T) int) and write a bunch of functions to glue them together / handle useful operations.

That impacts the readability of a long chain of calls, especially since Go doesn't have a lambda syntax to make things a bit tighter.

Getting rid of the limitation on method-level generics would make this _significantly_ more ergonomic.

discuss

order

No comments yet.