It is possible in Go to build a function that works on many different argument types—without duplicating any code. This is a generic function.
With type constraints, we can specify what types a generic function can receive. The types can be used within the function, during computations, as well.
Here we introduce a function that sums up the values in a slice that are below the value 10. With generics, we support many numeric types like int
, uint
, and int64
.
SumValuesLessThan10
function has a type parameter T that can be an int
, uint
, int64
, or uint8.for
-loop to see which elements are below the value 10, and then add them up.func
, we create 4 different slices of the supported element types, and pass them to SumValuesLessThan10
.package main
import (
"fmt"
)
// Part 1: specify generic method with T type that has 4 possible underlying types.
func SumValuesLessThan10[T int | uint | int64 | uint8](t []T) T {
// Part 2: loop over and sum up slice elements, and then return the sum.
result := T(0)
for _, n := range t {
if n < 10 {
result += n
}
}
return result
}
func main() {
// Part 3: create slices of varying types and call the generic method.
slice := []int{4, 5, 50}
fmt.Println(SumValuesLessThan10(slice))
slice2 := []uint{4, 5, 50}
fmt.Println(SumValuesLessThan10(slice2))
slice3 := []int64{4, 5, 999999999999999999}
fmt.Println(SumValuesLessThan10(slice3))
slice4 := []uint8{4, 5, 100}
fmt.Println(SumValuesLessThan10(slice4))
}9
9
9
9
With generics in Go, we use names like T, K, U and V to indicate generic parameters. We can constrain these parameters to certain types with an expression within the function type itself.