作为学习指针与值接收器的一部分,我提到了:https://gobyexample.com/methods
// This `area` method has a _receiver type_ of `*rect`.
func (r *rect) area() int {
return r.width * r.height
}
// Methods can be defined for either pointer or value
// receiver types. Here's an example of a value receiver.
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
func main() {
r := rect{width: 10, height: 5}
// Here we call the 2 methods defined for our struct.
fmt.Println("area: ", r.area())
fmt.Println("perim:", r.perim())
// Go automatically handles conversion between values
// and pointers for method calls. You may want to use
// a pointer receiver type to avoid copying on method
// calls or to allow the method to mutate the
// receiving struct.
rp := &r
fmt.Println("area: ", rp.area())
fmt.Println("perim:", rp.perim())
}
我不明白-->
rp := &r
rp is a pointer or address of r
为什么结果:
rp.area() is identical to r.area()
rp.perim() is identical to r.perim()
指针 :它们是内存中 var 的地址。
功能区() 需要一个指针接收器。所以这是明确的rp.area()(因为rp是r的指针或地址)
但是为什么这个r.area()?r 不是指针,而是值
同样,perim需要一个值,我们使用指针作为接收器?rp.perim()
这也意味着什么:
您可能希望使用指针接收器类型,以避免在方法调用时进行复制,或允许方法改变接收结构。
to avoid copying on method calls or to allow the method to mutate the receiving struct.
LEATH
相关分类