Type Parameters Syntax
Generic functions and types with [T any]
Generics background
Before Go 1.18, code that worked on multiple types required either interface{}/any (losing type safety) or code generation. Generics add type parameters for compile-time polymorphism.
Generic function syntax
Declare type parameters in square brackets after the function name:
func Map[T, U any](s []T, f func(T) U) []U {
result := make([]U, len(s))
for i, v := range s {
result[i] = f(v)
}
return result
}
nums := Map([]int{1,2,3}, func(n int) string {
return strconv.Itoa(n)
})