Go Generics
Generics let one function work with many types. Type parameters go in square brackets.
ExampleGo
package main
import "fmt"
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](items []T) T {
var total T
for _, v := range items {
total += v
}
return total
}
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, v := range items {
out = append(out, f(v))
}
return out
}
func main() {
fmt.Println(Sum([]int{1, 2, 3}))
fmt.Println(Sum([]float64{1.5, 2.5}))
fmt.Println(Map([]int{1, 2, 3}, func(n int) string { return fmt.Sprint(n * 10) }))
}Output
6 4 [10 20 30]
Quick check
What is T in func Sum[T Number]?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.