Golang方法指针作为接收器。

huangapple go评论89阅读模式
英文:

golang method pointer to receiver

问题

我有以下的结构体和代码:

type Person struct {
    Name    string
}

steve := Person{Name: "Steve"}

你能解释一下以下两个方法(一个使用指针作为接收者,一个不使用指针作为接收者)是如何都能打印出 p.Name 的吗?

func (p *Person) Yell() {
    fmt.Println("Hi, my name is", p.Name)
}

func (p Person) Yell(){
    fmt.Println("YELLING MY NAME IS", p.Name)
}

steve.Yell()

当直接指向 Person 结构体时(而不是实例 steve),难道 Name 不存在吗?

英文:

I have the following struct and :

type Person struct {
	Name    string
}


steve := Person{Name: "Steve"}

Can you explain how the following 2 methods (one without the pointer and one with in the receiver) both are able to print the p.Name?

func (p *Person) Yell() {
	fmt.Println("Hi, my name is", p.Name)
}

func (p Person) Yell(){
	fmt.Println("YELLING MY NAME IS", p.Name)
}

steve.Yell()

Wouldn't the Name not exist when pointing straight to the Person (not the instance steve?)

答案1

得分: 4

两者都指向实例,但是(p Person)每次调用函数时都指向一个新的副本,而(p *Person)始终指向同一个实例。

请查看这个示例:

func (p Person) Copy() {
    p.Name = "Copy"
}

func (p *Person) Ptr() {
    p.Name = "Ptr"
}

func main() {
    p1, p2 := Person{"Steve"}, Person{"Mike"}
    p1.Copy()
    p2.Ptr()
    fmt.Println("copy", p1.Name)
    fmt.Println("ptr", p2.Name)
}

还可以阅读Effective Go,这是一个对该语言非常有用的资源。

英文:

Both point to the instance, however (p Person) points to a new copy every time you call the function, where (p *Person) will always point to the same instance.

Check this example :

func (p Person) Copy() {
	p.Name = "Copy"
}

func (p *Person) Ptr() {
	p.Name = "Ptr"
}

func main() {
	p1, p2 := Person{"Steve"}, Person{"Mike"}
	p1.Copy()
	p2.Ptr()
	fmt.Println("copy", p1.Name)
	fmt.Println("ptr", p2.Name)
}

Also read Effective Go, it's a great resource to the language.

huangapple
  • 本文由 发表于 2014年6月10日 10:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/24131947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定