2016-12-03 60 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

相關問題