其他分享
首页 > 其他分享> > Go-复习-方法receiver

Go-复习-方法receiver

作者:互联网

package main

import (
"fmt"
)

type Ball struct {
Name string
}

func (b *Ball) Ping() {
fmt.Printf("Ping ,%p\n", b)
b.Name=b.Name+"Ping"
}

func (b Ball) Pong() {
fmt.Printf("Pong ,%p\n", &b)
b.Name=b.Name+"Pong"
}

func main() {
v := Ball{}
v.Name = "wjc"
fmt.Printf("v ,%p\n", &v)
v.Ping()
v.Pong()
fmt.Println(v.Name)

v1 := new(Ball)
v1.Name = "kelvin"
fmt.Printf("v1 ,%p\n", 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一份

标签:Ball,Name,fmt,Ping,v1,receiver,Go,Pong,复习
来源: https://www.cnblogs.com/wanjch/p/11549701.html