我聽到很多人談?wù)?Go,以及它如何不支持繼承。在真正使用語言之前,我只是隨波逐流,聽著聽著說。在稍微弄亂語言之后,開始掌握基礎(chǔ)知識。我遇到了這個場景: package maintype Thing struct { Name string Age int}type UglyPerson struct { Person WonkyTeeth bool}type Person struct { Thing}type Cat struct { Thing}func (this *Cat) SetAge(age int){ this.Thing.SetAge(age)}func (this *Cat GetAge(){ return this.Thing.GetAge() * 7}func (this *UglyPerson) GetWonkyTeeth() bool { return this.WonkyTeeth}func (this *UglyPerson) SetWonkyTeeth(wonkyTeeth bool) { this.WonkyTeeth = wonkyTeeth}func (this *Thing) GetAge() int { return this.Age}func (this *Thing) GetName() string { return this.Name}func (this *Thing) SetAge(age int) { this.Age = age}func (this *Thing) SetName(name string) { this.Name = name}現(xiàn)在,它的作用是從事物結(jié)構(gòu)組成 Person 和 Cat 結(jié)構(gòu)。通過這樣做,不僅 Person 和 Cat 結(jié)構(gòu)與 Thing Struct 共享相同的字段,而且通過組合,Thing 的方法也被共享。這不是繼承嗎?也通過實現(xiàn)這樣的接口:type thing interface { GetName() string SetName(name string) SetAge(age int)}所有三個結(jié)構(gòu)現(xiàn)在都已加入,或者我應(yīng)該說,可以以同構(gòu)的方式使用,例如“事物”數(shù)組。所以,我交給你了,這不是傳承嗎?編輯添加了一個名為“丑陋的人”的新派生結(jié)構(gòu),并覆蓋了 Cat 的 SetAge 方法。
3 回答

慕森卡
TA貢獻1806條經(jīng)驗 獲得超8個贊
這叫做組合。Person 或 Cat 的方法無法直接訪問 Thing 的字段。此外,如果例如 Cat 實現(xiàn)了自己的 SetAge() 并且您想調(diào)用 Thing 之一,則必須調(diào)用 myCat.Thing.SetAge(42) 而不是 myCat.SetAge(42)。
- 3 回答
- 0 關(guān)注
- 296 瀏覽
添加回答
舉報
0/150
提交
取消