Type Lists
Along with generics, Go introduced type-set interfaces. These interfaces list specific concrete types rather than methods.
Syntax: Type Lists
Use the pipe | symbol to define a set of allowed types.
type Number interface {
int | int64 | float64
}
func Add[T Number](a, b T) T {
return a + b
}
The ~ Symbol (Underlying Types)
If you want to match any type that has a specific underlying type (e.g., custom types based on int), use the ~ prefix.
type MyInt int
type Number interface {
~int | ~float64
}
// Add can now accept both int and MyInt
Common Constraint: Ordered
The Ordered constraint (often found in the golang.org/x/exp/constraints package) is a type list of all types that support comparison operators like < and >.
func Min[T Ordered](a, b T) T {
if a < b {
return a
}
return b
}