我是 go
的初学者,但我有一个问题:
我有以下代码:
package lab
import (
"fmt"
"math"
)
type Circle struct {
x float64
y float64
r float64
}
func (c *Circle) area() float64 {
return math.Pi * c.r * c.r
}
func StructCode() {
c := Circle{1,2,5}
fmt.Println("struct addr",c)
fmt.Println("Circle",c.area())
}
我的问题是,Circle area function
接受一个Circle Pointer
并返回面积。基于此。 为什么当我打印结构时它不显示内存地址,而是显示 &{1 2 5}
而不是。它需要一个用于区域函数的指针,但 c circle
没有作为指针打印(我想它会打印一个内存地址作为一个 circle pointer
)
更新
除非 &{1 2 5}
实际上是引用?
第二次更新
我能够做到这一点:
c := Circle{1,2,5}
p := &c
fmt.Printf("%p",p)
// returns 0xc042052340
但是我现在的问题是,为什么我可以传递 c.area()
而不是 p.area()
因为圆的面积函数需要一个指针:
最佳答案
当我们以值作为接收者调用指针接收者方法时。 Go 将函数调用 c.area()
解释为 (&c).area()
。这种便利是go本身提供的。
在 Golang规范它是函数调用被描述为
A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()
关于pointers - 在 golang 中返回一个指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50658327/