我有以下struct
,其功能可以更新其字段:
type Dog struct {
name string
age int
}
func (dog *Dog) growOld() {
dog.name = "old dog"
dog.age++
}
上面的方法可以正常工作。但是,当struct
属于另一个对象并且所述对象告诉struct
更新其字段时,更改似乎发生了,但没有应用:
package main
import (
"fmt"
)
type Owner struct {
dog Dog
}
func newOwner(dog Dog) Owner {
var owner Owner
owner.dog = dog
return owner
}
func (owner Owner) tellDogToGrowOld() {
owner.dog.growOld()
}
func main() {
var dog Dog
dog.name = "dog"
owner := newOwner(dog)
owner.tellDogToGrowOld()
fmt.Println(dog) // dog's name is still `dog` and age is 0.
}
我认为我必须以某种方式使用pointers
,但不能完全弄清楚。
答案 0 :(得分:4)
如果您希望方法修改接收者的状态,则该方法的接收者的类型应为指针类型。
也就是说,与声明growOld
方法的方式相同,tellDogToGrowOld
方法还应具有一个指针接收者:
func (owner *Owner) tellDogToGrowOld() {
owner.dog.growOld()
}
或者,您可以将要修改的字段设置为指针,例如:
type Owner struct {
dog *Dog
}
func newOwner(dog *Dog) Owner {
var owner Owner
owner.dog = dog
return owner
}
func (owner Owner) tellDogToGrowOld() {
owner.dog.growOld()
}
答案 1 :(得分:3)
将所有者中的字段设置为*狗不是狗
type Owner struct {
dog *Dog
}
func newOwner(dog *Dog) Owner {
var owner Owner
owner.dog = dog
return owner
}
从主要用途&dog呼叫时
var dog Dog
dog.name = "dog"
owner := newOwner(&dog)