In an earlier entry, I showed that a stronger constraint to only accept values whose concrete types allow equality operations (e.g., ==) is possible with comparable (e.g., use is Contains[T comparable]). How about constraint for specific types?
In the example below, Sum, a generic function, only accepts value of type T if the concrete types are either int, int64, or float64. The good thing about this is that compile-time error is detected when you pass invalid values to the function such as string values.
type Number interface {
int | int64 | float64
}
func main() {
fmt.Println(Sum(1, 2))
fmt.Println(Sum(1.34, 1.34))
// fmt.Println(Sum("a", "b")) // error: string does not satisfy Number (string missing in int | int64 | float64)
}
func Sum[T Number](v1 T, v2 T) T {
return v1 + v2
}