Generics#
Go 1.18+ has parametric polymorphism via type parameters.
A generic function over any element type.
func Head[T any](xs []T) (T, bool) {
var zero T
if len(xs) == 0 { return zero, false }
return xs[0], true
}
Call site inferring T.
n, ok := Head([]int{1, 2, 3})
Constraints live in the constraints package (now mostly
cmp.Ordered plus user-defined sets).
func Max[T cmp.Ordered](a, b T) T {
if a > b { return a }
return b
}
References#
Interfaces for the interface-based constraint mechanism.