英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论