←back to thread

Constraints in Go

(bitfieldconsulting.com)
210 points gus_leonel | 1 comments | | HN request time: 0.001s | 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. tapirl ◴[] No.42164982[source]
The difference between types.Implements and types.Satisfies is mainly caused by a history reason. It is just a tradeoff between keeping backward compatibility and theory perfection.

It is pity that Go didn't support the "comparable" interface from the beginning. If it has been supported since Go 1.0, then this tradeoff can be avoided.

There are more limitations in current Go custom generics, much of them could be removed when this proposal (https://github.com/golang/go/issues/70128) is done.

I recommend people to read Go Generics 101 (https://go101.org/generics/101.html, author here) for a thoroughly understanding the status quo of Go custom generics.