You can't add generic parameters in methods. This means you can't implement a Map method on a slice, unless it's going to either A: return the same type as the slice or B: you explicitly decide at slice creation time what the one destination type you're going to have is and pass that as a parameter. This significantly limits "map" implementations, as well as "reduce". It does leave "filter" as a possible thing you can implement, since that's a hard-coded bool type.
Example: https://go.dev/play/p/as3rT4fB3cn
// Invocation:
strings := []string{"1", "2", "3"}
ints, err := Mapper[string, int](strings).MapErr(strconv.Atoi)
strings = Mapper[string, string](strings).Map(func(s string) string {
return s + "_suffix"
})
// Definition:
type Mapper[T, U any] []T
func (ts Mapper[T, U]) Map(f func(T) U) (us []U) {
us, _ = ts.MapErr(func(t T) (u U, err error) {
u = f(t)
return
})
return
}
func (ts Mapper[T, U]) MapErr(f func(T) (U, error)) (us []U, err error) {
us = make([]U, 0, len(ts))
for _, t := range ts {
var u U
u, err = f(t)
if err != nil {
return
}
us = append(us, u)
}
return
}As a potentially useful technique in the general sense it makes good sense to know. As a solution to making map & reduce practical functions to use in Go, it makes me wonder just how much crap it takes for people to notice that just because a pattern is fun to use in one language, it isn't appropriate for another. I mean, how painful does it have to be, exactly?
Also, some people just insist on chaining, which this won't enable. (At least not without even more gymnastics.)