2016-12-03 41 views
2

我正在试验GoLang和接口和结构继承。为什么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://play.golang.org/p/OxzuaQkafj

然而,当我运行的主要方法,年龄仍然是“21”,而不是由SetAge()方法更新。

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

回答

4

您的函数接收器是值类型,所以它们被复制到您的函数范围中。为了影响接收到的类型在函数的生命周期之后,接收器应该是一个指向你的类型的指针。见下文。

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

不能相信我错过了 - 谢谢! 我应该明确地停止编码并进入睡眠状态。 – Stephen

相关问题