为什么SetAge()方法不能正确设置年龄?

为什么SetAge()方法不能正确设置年龄?,第1张

为什么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)}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5008099.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-14
下一篇2022-11-14

发表评论

登录后才能评论

评论列表(0条)

    保存