Type sets
A type set is the collection of types that satisfy a constraint. Interfaces used as constraints can list types with | and can embed other constraints, which is how ~int | ~int64 means "these integers or any named type whose underlying type is one of them."
Detailed Explanation
When you write func Add[T int | int64](a, b T) T, the constraint int | int64 is a type set: T may be int or int64. Inside the function you may use operations that every type in the set supports — here, +. The compiler rejects Add("a", "b") because string is not in the set.
~ means underlying type. type Count int is not int. T int does not accept Count. T ~int does. Almost every useful numeric constraint uses ~ so user-defined aliases of integers still work. constraints.Integer in golang.org/x/exp/constraints (and similar helpers) is a union of ~ integer types.
Interfaces as constraints. A constraint is an interface. Ordinary method interfaces (interface { Error() string }) have a type set of all types that have that method. Constraint-only syntax — unions, ~, and mixes of both — is legal only in constraint position, not as the type of a variable. You cannot write var x int | string.
Intersection is embedding. interface { ~int; String() string } is the types whose underlying type is int and that have String(). Both must hold. This is how you say "ordered and printable" without a new keyword.
comparable is a predeclared constraint. Its type set is every type that supports ==. Slices, maps, and functions are not in it. A struct is in it only if every field is. You need comparable for map keys and for == on T.
Empty type set. A constraint that contradicts itself (interface { ~int; ~string }) has no types. A function with that constraint can never be instantiated. The compiler reports that when you try to use it, and some versions also when you declare it.
What it costs. Tight type sets give you operators and catch mistakes. Loose sets (any) force you back to reflection or panics. Start with cmp.Ordered or comparable when they match the operations you need, and write a union only when those are too wide or too narrow.
Code Examples
package main
import "fmt"
func Add[T ~int | ~int64](a, b T) T {
return a + b
}
type Count int
func main() {
fmt.Println(Add(1, 2), Add(Count(3), Count(4)))
}type Stringer interface {
String() string
}
func label[T Stringer](v T) string {
return v.String()
}func same[T comparable](a, b T) bool {
return a == b
}Common Gotchas
Union syntax is not a value type
`var x int | string` does not compile. Use a constraint on a type parameter, or a named interface in ordinary code without unions.
Without `~`, named types are excluded
`func f[T int](T)` rejects `type Count int`. Write `~int` if you want `Count`.
`comparable` does not include slices
a generic `Equal` for `[]T` must compare in a loop, even if `T` is comparable.
Method constraints and type sets compose by embedding
read `interface { A; B }` as "in both sets."