Generic parameters to Go functions
// Generic Functions in Go
package main
import "fmt"
func squareSlice[T any, M any](a []T, f func(T) M) []M {
n := make([]M, len(a))
for i, e := range a {
n[i] = f(e)
}
return n
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
squaresInts := squareSlice(numbers, squareInt[int])
// input in `int` format
fmt.Println("numbers = ", numbers)
// output in `int` format
fmt.Println("squaresInts = ", squaresInts)
floats := []float64{1.9, 2.6, 3.4, 4.2, 5.1}
squaresFloats := squareSlice(floats, squareFloat[float64])
// input in `float64` format
fmt.Println("floats = ", floats)
// output in `float64` format
fmt.Println("squaresFloats = ", squaresFloats)
}
// The `squareInt` function returns the square of an integer.
func squareInt[T int](x T) T {
return x * x
}
// The `squareFloat` function returns the square of an integer.
func squareFloat[T float64](x T) T {
return T(int(x) * int(x))
}