The problem with type set constraint like Number below is that it only accepts exactly the given types, but not the custom named types. This is demonstrated when x is used in the call to Sum function. This is resolved by allowing named types using ~.
type Number interface {
int | int64 | float64
}
type Number1 int
func main() {
var x Number1
x = 1
fmt.Println(Sum(x, x)) // Number1 does not satisfy Number (possibly missing ~ for int in Number)
}
func Sum[T Number](v1 T, v2 T) T {
return v1 + v2
}
By redefining the new interface type below, the compile-time error does not show anymore since the constraint is more permissive.
type Number interface {
~int | ~int64 | ~float64
}
type Number1 int
func main() {
var x Number1
x = 1
fmt.Println(Sum(x, x))
}
go run .
2