Generics in Go
Type parameters and constraint interfaces.
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](items []T) T {
var total T
for _, item := range items {
total += item
}
return total
}
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, item := range items {
out = append(out, f(item))
}
return out
}
How it works
- A constraint interface unions the allowed types.
~intincludes types whose underlying type is int.Map[T, U any]transforms between element types.
Keywords and builtins used here
anyappendfloat64forfuncintint64interfacelenmakerangereturntypevar
The run, in numbers
- Lines
- 19
- Characters to type
- 310
- Tokens
- 108
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 59 seconds.
Step 1 of 4 in Generics, step 13 of 19 in Interfaces & generics.