为什么SetAge()方法不能正确设置年龄? [英] Why does the SetAge() method not set the age correctly?

查看:35
本文介绍了为什么SetAge()方法不能正确设置年龄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试GoLang,接口和结构继承.

I'm experimenting with GoLang and interfaces and struct inheritence.

我创建了一组结构,我可以将常见的方法和值保留在核心结构中,然后继承该结构并适当添加其他值:

I've created a set of structures with the idea that I can keep common methods and values in a core structure an then just inherit this and add extra values as appropriate:

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)
}

您还可以在下面的游乐场中找到

Which you can also find here in the go playground:

https://play.golang.org/p/OxzuaQkafj

但是,当我运行main方法时,年龄保持为"21",并且不会被SetAge()方法更新.

However when I run the main method, the age remains as "21" and isn't updated by the SetAge() method.

我试图了解为什么会这样,以及我需要做些什么才能使SetAge正常工作.

I'm trying to understand why this is and what I'd need to do to make SetAge work correctly.

推荐答案

您的函数接收者是值类型,因此将它们复制到您的函数范围中.为了在函数的生命周期之后影响您收到的类型,您的接收者应该是指向您类型的指针.见下文.

Your function receiver's are value types, so they are copied into your function scope. To affect your received type past the lifetime of the function your receiver should be a pointer to your type. See below.

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()方法不能正确设置年龄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆