为什么SetAge()方法不能正确设置年龄?
我正在尝试使用GoLang,接口和结构继承。
我创建了一组结构,其想法是可以将常见方法和值保留在核心结构中,然后仅继承此结构并适当添加其他值:
type NamedThing interface { GetName() string
GetAge() int
SetAge(age int)
}
type BaseThing struct {
name string
age int
}
func (t BaseThing) GetName() string {
return t.name
}
func (t BaseThing) GetAge() int {
return t.age
}
func (t BaseThing) SetAge(age int) {
t.age = age
}
type Person struct {
BaseThing
}
func main() {
p := Person{}
p.BaseThing.name = "fred"
p.BaseThing.age = 21
fmt.Println(p)
p.SetAge(35)
fmt.Println(p)
}
您还可以在下面的游乐场中找到:
https://play.golang.org/p/OxzuaQkafj
但是,当我运行main方法时,年龄保持为“ 21”,并且不会被SetAge()方法更新。
我试图了解为什么会这样,以及我需要做些什么才能使SetAge正常工作。
回答:
您的函数接收者是值类型,因此它们被复制到您的函数范围中。为了在函数的生存期内影响您收到的类型,您的接收者应该是指向您类型的指针。见下文。
type NamedThing interface { GetName() string
GetAge() int
SetAge(age int)
}
type BaseThing struct {
name string
age int
}
func (t *BaseThing) GetName() string {
return t.name
}
func (t *BaseThing) GetAge() int {
return t.age
}
func (t *BaseThing) SetAge(age int) {
t.age = age
}
type Person struct {
BaseThing
}
func main() {
p := Person{}
p.BaseThing.name = "fred"
p.BaseThing.age = 21
fmt.Println(p)
p.SetAge(35)
fmt.Println(p)
}
以上是 为什么SetAge()方法不能正确设置年龄? 的全部内容, 来源链接: utcz.com/qa/417524.html