package main
import (
"fmt"
)
type Ball struct {
Name string
}
func (b *Ball) Ping() {
fmt.Printf("Ping ,%p ", b)
b.Name=b.Name+"Ping"
}
func (b Ball) Pong() {
fmt.Printf("Pong ,%p ", &b)
b.Name=b.Name+"Pong"
}
func main() {
v := Ball{}
v.Name = "wjc"
fmt.Printf("v ,%p ", &v)
v.Ping()
v.Pong()
fmt.Println(v.Name)
v1 := new(Ball)
v1.Name = "kelvin"
fmt.Printf("v1 ,%p ", v1)
v1.Ping()
v1.Pong()
fmt.Println(v1.Name)
}
输出:
v ,0xc0000301f0
Ping ,0xc0000301f0
Pong ,0xc000030200
wjcPing
v1 ,0xc000030220
Ping ,0xc000030220
Pong ,0xc000030230
kelvinPing
所以:
struct 的实例和实例指针都可以调用值类型和指针类型 receiver 的方法。调用指针类型receiver的方法时,相当于传引用。值接受者,编译器copy一份
但是:接口类型赋值时,值变量不能给赋值给方法为指针接受者的接口