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

Ste*_*hen 2 go

我正在尝试 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)
}
Run Code Online (Sandbox Code Playgroud)

您还可以在 go Playground 中找到:

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

但是,当我运行 main 方法时,年龄仍为“21”,并且不会由 SetAge() 方法更新。

我试图理解这是为什么以及我需要做什么才能使 SetAge 正常工作。

saa*_*rrr 5

您的函数接收者是值类型,因此它们被复制到您的函数作用域中。为了影响你接收到的类型超过函数的生命周期,你的接收者应该是一个指向你的类型的指针。见下文。

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)
}
Run Code Online (Sandbox Code Playgroud)