I was surprised that the new Go generics could not handle generic method parameters, see below.
I wanted to accept a function that accepts Generic type T but return the functions return type R.
I was wondering if:
a) Anyone knows why? maybe Go doesn’t truly support monomorphization for generics, which is what I suspect?
b) Does anyone know if this is at all possible without having the type parameter on the struct itself?
package main
import (
"fmt"
)
type MyThing[T any] struct {
value T
}
func (m MyThing[T]) Perform[R any](f func(T) R) R {
return f(m.value)
}
func main() {
fmt.Println("Hello, playground")
}
// output: syntax error: method must have no type parameters
Go Generics - Blog Title
Note that this is very unlikely to change since accepting type parameters on methods would make interface matching odd and surprising.