Type parameters and constraints in Go
A constraint says what the type must support, and any is the loosest.
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](values []T) T {
var total T
for _, value := range values {
total += value
}
return total
}
func Max[T cmp.Ordered](values []T) (T, bool) {
var best T
if len(values) == 0 {
return best, false
}
best = values[0]
for _, value := range values[1:] {
if value > best {
best = value
}
}
return best, true
}
func Unique[T comparable](values []T) []T {
seen := make(map[T]struct{}, len(values))
var out []T
for _, value := range values {
if _, ok := seen[value]; !ok {
seen[value] = struct{}{}
out = append(out, value)
}
}
return out
}
How it works
comparableallows == and map keys.cmp.Orderedallows < and >.- A union constraint lists the types you accept.
Keywords and builtins used here
appendboolcomparablefloat64forfuncifintint64interfacelenmakemaprangereturnstructtypevar
The run, in numbers
- Lines
- 37
- Characters to type
- 599
- Tokens
- 196
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 107 seconds.
Step 2 of 4 in Generics, step 14 of 19 in Interfaces & generics.