I am not familiar with generics in Go, but I’ve seen this specific question about wanting a Map function all over Reddit and it’s my understanding that you cannot do this because only top-level functions can have multiple generic parameters.
@jaco If you drop the requirement for defining a custom slice type, the map works well:
func Map[T, S any](t []T, fct func(x T) S) []S {
var s []S
for _, x := range t {
s = append(s, fct(x))
}
return s
}
func main() {
t := []int{1, 2, 3}
s := Map(t, func(n int) int64 {
return int64(n)
})
fmt.Println(s)
}
The point is, the built-in slice type is generic already, thus a custom generic slice type might not be necessary (unless it is needed for some other reason).
Agreed, nested functions are harder to read than chained ones, but OTOH, code using custom generic slice types is (usually) also harder to read than code using standard slices.