3 ms·
type IntBox struct { v int } type StrBox struct { v string } func (b IntBox) MapToStr(f func(int) string) StrBox { return StrBox{v: f(b.v)}
by LukeShu 2mo ago
type IntBox struct { v int }
type StrBox struct { v string }
func (b IntBox) MapToStr(f func(int) string) StrBox {
return StrBox{v: f(b.v)}
}
(Please forgive any typos I made on mobile.)
It wasn't a great example because "Box" isn't really a useful type. But the point is that you no longer need to define a separate "MapToXXX" method for every type you might want to map to; now you can have just one type-generic "Map" method.
- majewsky 2mo ago> "Box" isn't really a useful type. It is very close to one. My Option[T] type [1] cannot have a Map method in stable Go because of the type system restriction in question. Instead, I have a separate package with freestanding functions with the same purpose, including Map [2]. [1] https://pkg.go.dev/go.xyrillian.de/gg/option#Option https://pkg.go.dev/go.xyrillian.de/gg/option#Option [2] https://pkg.go.dev/go.xyrillian.de/gg/options#Map https://pkg.go.dev/go.xyrillian.de/gg/options#Map