Home > Backend Development > Golang > 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

王林
Release: 2019-12-24 16:46:12
Original
3717 people have browsed it

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
}
Copy after login

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)
Copy after login

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)
Copy after login

or

func (a Integer) Add(b Integer) Integer {    
return  a + b
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template