A type constraint restricts which types may fill a generic type parameter. It lets one function or data structure work across multiple types while preserving the operations those types support. section 7.1.1 section 7.6
Common constraints provide progressively specific guarantees:
- any accepts every type, making it the least-constraining option. section 7.1.1
- comparable permits equality comparisons with ==, while constraints.Ordered permits >, <, >=, and <=. section 7.6
- Union-based constraints list permitted types, such as int, int32, and int64. section 7.1.1
- The ~ operator includes defined types whose underlying type matches a listed type. section 7.1.1
Constraining a summable type
type summable interface { int | int32 | int64 } permits only the listed integer types. Changing it to type summable interface { ~int | ~int32 | ~int64 } also permits defined types such as age int.
Using a constrained generic function
A function declared as func sortSlice[T constraints.Ordered](t []T) ([]T, error) can be called with sortSlice([]int{1,4,3,2}); the compiler infers T from the argument. section 7.6





