Merge pull request #2649 from nspcc-dev/fix-unnamed-rcvr

compiler: fix nil method receiver handling
This commit is contained in:
Roman Khimov 2022-08-18 12:23:17 +03:00 committed by GitHub
commit 6082383e3c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 1 deletions

View file

@ -493,8 +493,15 @@ func (c *codegen) convertFuncDecl(file ast.Node, decl *ast.FuncDecl, pkg *types.
// to support other types.
if decl.Recv != nil {
for _, arg := range decl.Recv.List {
// Use underscore instead of unnamed receiver name, e.g.:
// func (MyCustomStruct) DoSmth(arg1 int) {...}
// Unnamed receiver will never be referenced, thus we can use the same approach as for multiple unnamed parameters handling, see #2204.
recvName := "_"
if len(arg.Names) != 0 {
recvName = arg.Names[0].Name
}
// only create an argument here, it will be stored via INITSLOT
c.scope.newVariable(varArgument, arg.Names[0].Name)
c.scope.newVariable(varArgument, recvName)
}
}

View file

@ -385,3 +385,17 @@ func TestUnusedFunctions(t *testing.T) {
eval(t, src, big.NewInt(2231))
})
}
func TestUnnamedMethodReceiver(t *testing.T) {
src := `package foo
type CustomInt int
func Main() int {
var i CustomInt
i = 5
return i.Do(2)
}
func (CustomInt) Do(arg int) int {
return arg
}`
eval(t, src, big.NewInt(2))
}