Generic methods

Hi,
Say i want to implement a “map” function on generic slices with go1.18beta1… The method’s prototype should be something like:

func (xs List[T]) Map(fct func(x T) S) List[S] {...} assuming List[T] is defined as:

type List[T any] []T

Unfortunately, i’ve no found how to introduce the S generic in the method declaration. Is it even possible?

I am not familiar with generics in Go, but I’ve seen this specific question about wanting a Map function all over Reddit and it’s my understanding that you cannot do this because only top-level functions can have multiple generic parameters.

1 Like

Ok, thanks for the tip…

@jaco If you drop the requirement for defining a custom slice type, the map works well:

func Map[T, S any](t []T, fct func(x T) S) []S {
	var s []S
	for _, x := range t {
		s = append(s, fct(x))
	}
	return s
}

func main() {
	t := []int{1, 2, 3}
	s := Map(t, func(n int) int64 {
		return int64(n)
	})
	fmt.Println(s)
}

The point is, the built-in slice type is generic already, thus a custom generic slice type might not be necessary (unless it is needed for some other reason).

Yes, that’s what I’ll do… I preferred to have a dotted notation to simplify the call sequence, but never mind…

I find xs.map(fct).filter(pred) clearer than filter(map(xs, fct), pred)… But i can live with it…

1 Like

Agreed, nested functions are harder to read than chained ones, but OTOH, code using custom generic slice types is (usually) also harder to read than code using standard slices.