3 ms·
via https://rakyll.org/generics-facilititators/ https://rakyll.org/generics-facilititators/ Example: https://go.dev/play/p/as3rT4fB3cn https://go.dev/play/p/as
by robertsdionne 4y ago
via https://rakyll.org/generics-facilititators/ https://rakyll.org/generics-facilititators/
Example:
https://go.dev/play/p/as3rT4fB3cn 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
}
- deleted 4y ago[deleted]
- jerf 4y agoWhich people like to bring up, and does make it "possible" to do this style, but takes a style I think is already crazily and uselessly verbose and makes it even more verbose, especially once you take that "strconv.Atoi" and try to inline a function there, at which points the types from the earlier generic instantiation get to appear again. Hope you didn't give your types good, descriptive names! 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.)