4 ms·
Hold on. I'm still complaining about generics since its still not possible to write a generic map function on a struct.
by eweise 4y ago
Hold on. I'm still complaining about generics since its still not possible to write a generic map function on a struct.
- monocasa 4y agoCan you expand on that? I sort of divorced myself from golang right as the final generics implementation was starting to bake.
- jerf 4y agohttps://go.dev/doc/faq#generic_methods https://go.dev/doc/faq#generic_methods 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.
- robertsdionne 4y agovia 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.)