go: invalid AST: method must have no type parameters,methods cannot have type parameters
What version of Go are you using (go version
)?
$ go version go version devel go1.18-123393a535 Tue Oct 5 01:30:56 2021 +0000 windows/amd64
Does this issue reproduce with the latest release?
yes
What operating system and processor architecture are you using (go env
)?
go env
Output
$ go env
What did you do?
package main import ( "fmt" "sync" ) type A struct { mp sync.Map } func (a *A) Set(k string,v interface{}) { a.mp.Store(k,v) } func (a *A) Get[T any](k string) T { v,_:=a.mp.Load(k) return (interface{})(v).(T) } func NewA()*A{ return &A{mp:sync.Map{}} } func main() { a:=NewA() a.Set("a","1") fmt.Println(a.Get[string]("a")) }
https://go2goplay.golang.org/p/ZzVGxEHe9QP
What did you expect to see?
If everything is OK, he should return a value of type string
What did you see instead?
.\main.go:15:17: invalid AST: method must have no type parameters .\main.go:15:23: methods cannot have type parameters
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 1
- Comments: 17 (6 by maintainers)
Generic implementation is terrible
well it’s very inconvenient
I think the problem is in how generics works under the hood, in current implementation allowing type parameters in methods is impssible except using generics directly in type which owns this method. (@ianlancetaylor correct me please, if i’m wrong).
How to solve it? At this time, when this option is not allowed, try to build it in functional way, like
Is it shiny and cool-looking? Not really. But at least, this way is better than using interfaces before 1.18.
And btw: Hi people from future! 👋 We are you in the past, we still have these problems 🙃 Yeah, i know, i know, you have already flight cars already, and banned protobuf in your time, so i think now these issues is not a problem for you…
Right?..
This is working as intended
Ref: https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md#No-parameterized-methods
It looks weird if it doesn’t support method types