←back to thread

Constraints in Go

(bitfieldconsulting.com)
210 points gus_leonel | 1 comments | | HN request time: 0.207s | 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 #
rendaw ◴[] No.42164004[source]
There are tons of random limitations not present in other languages too, like no generic methods.
replies(2): >>42164827 #>>42170829 #
bigdubs ◴[] No.42164827[source]
That's not a random limitation, there are very specific reasons[1] you cannot easily add generic methods as struct receiver functions.

[1] https://go.googlesource.com/proposal/+/refs/heads/master/des...

replies(2): >>42165247 #>>42168728 #
abound ◴[] No.42165247[source]
For someone not well-versed in language implementation details, it may very well feel random.

I've been using Go as my primary language for a decade, and the lack of generics on methods was surprising to me the first time I ran into it, and the reasoning not obvious.

replies(1): >>42169404 #
1. rendaw ◴[] No.42169404[source]
Yeah. I'm not claiming they didn't back themselves into a corner here.

There's no theoretical reason not to have it, the reason is because of a random intersection of other design decisions... unless you're saying they made those choices fully expecting to have these restrictions on generics later?