Constraints
any allows everything and therefore forbids operators. Comparison and order require a constraint.
With the constraint any you cannot write a < b: the compiler does not know whether T has an order. A constraint says what the type can do.
func Max[T cmp.Ordered](a, b T) T {
if a > b {
return a
}
return b
}
cmp.Ordered covers numbers and strings. Max(3, 8) and Max("go", "py") call one function. Your own interface can be a constraint too:
type Number interface {
~int | ~int64 | ~float64
}
A tilde means "a type whose underlying type is this". type Money int64 falls under ~int64. Without the tilde only int64 itself would fit, and a named type would stay outside. A union is written with |.
comparable allows == and !=. The keys of a generic map ask for it. Not every comparable is ordered, and not every ordered type should be used as a key without thinking: slices are not comparable.
Keep a constraint narrow. If a function needs only order, do not ask for an interface with three methods. If it needs the method Write, that is the ordinary interface io.Writer, and a generic is not required: a parameter of an interface type is simpler. A generic wins when the result also depends on T and an interface would erase the concrete type.
Practice
Why a constraint
Why does
func Max[T any](a, b T) Twith the bodyif a > bnot compile?- The sign > is always forbidden in generics
- any does not guarantee that the values can be ordered
- You need to write a.Greater(b)
- It compiles, but panics on strings
The greater of two
Write
Max[T cmp.Ordered](a, b T) T. Return the greater argument. If they are equal, return either one — they match.A tilde in a constraint
The constraint says
~int64. What else falls into the type, besidesint64itself?- Only pointers *int64
- Named types whose underlying type is int64
- Any numbers, including float64
- Only constants