capypad
0 day streak
go / expert
Snippet

Generic Type Set Constraints

Type sets in interfaces allow generics to restrict types to a specific union. The tilde (~) operator includes types that share the same underlying primitive type.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
type Number interface {
~int | ~int64 | ~float64
}
 
func Sum[T Number](vals []T) T {
var total T
for _, v := range vals {
total += v
}
return total
}
Breakdown
1
~int | ~int64 | ~float64
Defines a union of allowed types including custom types based on these primitives.
2
func Sum[T Number]
A generic function signature constrained by the Number interface.