0

I'm trying to write a generic List container in Go so I can better learn how type parameters work.

Currently I'm working on a Map method that takes in a mapper function and returns a new list that has every element mapped.

Here is a part of the code:

type List[T any] []*T

func (list List[T]) Map[E](mapper func(int, *T) *E) List[E] {
    // Implementation details
}

This code will error out with "method must have no type parameters". Is there a way to properly do it without using List[interface{}] as the out type?

Paul Cosma
  • 303
  • 2
  • 11
  • 3
    No. You have to list all type parameters at the type declaration. – icza Mar 28 '22 at 20:27
  • The solution is define a function Map that receive your list and other parameters. This limitation may be fixed in the next versions of go – Tiago Peczenyj Mar 29 '22 at 02:31
  • 1
    See also the [Why does Go not support methods with type parameters?](https://go.dev/doc/faq#generic_methods) answer in the official Go FAQ, which includes: "The methods of a type determines the interfaces that the type implements, but it is not clear how this would work with parameterized arguments for methods of generic types. It would require either instantiating functions at run time or instantiating every generic function for every possible type argument. Neither approach seems feasible." – thepudds Mar 29 '22 at 18:02

0 Answers0