←back to thread

Constraints in Go

(bitfieldconsulting.com)
210 points gus_leonel | 1 comments | | HN request time: 0.211s | source
Show context
pansa2 ◴[] No.42163816[source]
I'm surprised by the complexity of Go's generic constraints, given the language's focus on simplicity. Things like the difference between "implementing" and "satisfying" a constraint [0], and exceptions around what a constraint can contain [1]:

> A union (with more than one term) cannot contain the predeclared identifier comparable or interfaces that specify methods, or embed comparable or interfaces that specify methods.

Is this level of complexity unavoidable when implementing generics (in any language)? If not, could it have been avoided if Go's design had included generics from the start?

[0] https://stackoverflow.com/questions/77445861/whats-the-diffe...

[1] https://blog.merovius.de/posts/2024-01-05_constraining_compl...

replies(5): >>42164004 #>>42164048 #>>42164801 #>>42164982 #>>42176376 #
1. burakemir ◴[] No.42164048[source]
Generics are a powerful mechanism, and there is a spectrum. The act of retrofitting generics on go without generics certainly meant that some points in the design space were not available. On the other hand, when making a language change as adding generics, one wants to be careful that it pulls its own weight: it would be be sad if generics had been added and then many useful patterns could not be typed. The design choices revolve around expressivity (what patterns can be typed) and inference (what annotations are required). Combining generics with subtyping and inference is difficult as undecidability looms. In a language with subtyping it cannot be avoided (or the resulting language would be very bland). So I think the answer is no, this part of the complexity could not have been avoided. I think they did a great job at retrofitting and leaving the basic style of the language intact - even if I'd personally prefer a language design with a different style but more expressive typing.