小编Ste*_*hen的帖子

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

您还可以在 go Playground 中找到:

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

但是,当我运行 …

go

2
推荐指数
1
解决办法
202
查看次数

标签 统计

go ×1