Home  >  Article  >  Backend Development  >  Analysis of the problem of not being able to obtain the address in golang

Analysis of the problem of not being able to obtain the address in golang

王林
王林Original
2019-12-24 16:46:123672browse

Analysis of the problem of not being able to obtain the address in golang

The code example is as follows:

func main() {
    var a Integer = 1
    var b Integer = 1
    sum := a.Add(b)
    fmt.Println(sum)

    var i interface{} = a
    sum = i.(Integer).Add(b) // 报错
    fmt.Println(sum)
}

type Integer int

func (a *Integer) Add(b Integer) Integer {
    return  *a + b
}

The error message is as follows:

test\testVar.go:16:19: cannot call pointer method on i.(Integer)
test\testVar.go:16:19: cannot take the address of i.(Integer)

This happens because the Add method requires an Integer pointer type The receiver, and the i.(Integer) we passed is a value, and this value is not assigned to any variable, so the symbol "&" cannot get the address.

The correct way is to assign i.(Integer) to a variable, or change the method receiver to a normal type.

Code examples are as follows:

   var i interface{} = a
    c := i.(Integer)
    sum = c.Add(b)
    fmt.Println(sum)

or

func (a Integer) Add(b Integer) Integer {    
return  a + b
}

Recommended related articles and tutorials: golang tutorial

The above is the detailed content of Analysis of the problem of not being able to obtain the address in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn