In my book Know Go, and in the previous tutorials in this series, you’ll learn all about generic programming in Go and the new universe of programs it opens up to us. Ironically, one of the new features of Go that gives us the most freedom is constraints. Let’s talk about that, and explain the paradox.
We saw in the previous tutorial that when we’re writing generic functions that take any type, the range of things we can do with values of that type is necessarily rather limited. For example, we can’t add them together. For that, we’d need to be able to prove to Go that they’re one of the types that support the + operator.
It’s the same with interfaces, as we discussed in the first post in this series. The empty interface, any, is implemented by every type, and so knowing that something implements any tells you nothing distinctive about it.
Similarly, in a generic function parameterised by some type T, constraining T to any doesn’t give Go any information about it. So it has no way to guarantee that a given operator, such as +, will work with values of T.