[generics] Rational for generic methods

81 views
Skip to first unread message

firel...@gmail.com

unread,
Jun 24, 2020, 1:02:23 AM6/24/20
to golang-nuts
Under "No parameterized methods", the design document states:

In Go, one of the main roles of methods is to permit types to implement interfaces. It is not clear whether it is reasonably possible to permit parameterized methods to implement interfaces.
[...]
Or, we could decide that parameterized methods do not, in fact, implement interfaces, but then it's much less clear why we need methods at all.

Parameterized methods that do not implement interfaces are very useful for expressibility, especially when it comes to fluent interfaces. The following is one example:

type Array(type T) []T

func (a Array(A)) Map(type B)(fn func(A) B) Array(B) {
   b := make([]B, len(a))
   for i := range a {
       b[i] = fn(a[i])
   }
   return b
}

func F() int {
   return Array(int){...}.
       Map(func(v int) int { return v*v }).
       Filter(func(v int) bool { return v%2 == 0 }).
       Sum(func(a, b int) int { return a+b })
}

For a larger example, see: https://gitlab.com/firelizzard/go-iter/-/blob/generic-methods/fluent/map.go2
Reply all
Reply to author
Forward
0 new messages