2 回答

TA貢獻1796條經驗 獲得超4個贊
Go 中沒有繼承。使用成分:
type common struct {
data DatumType
}
func (c *common) commonFunc() {
// Do something with data.
}
type derived1 struct {
common
otherField1 int
}
// Implement other methods on derived1.
type derived2 struct {
common
otherField2 string
}
// Implement other methods on derived2.

TA貢獻1815條經驗 獲得超10個贊
Go 沒有繼承。相反,它提供了嵌入的概念。
在這種情況下,您不需要/不想定義base為interface. 使其成為結構并將函數定義為方法。然后嵌入base到您的派生結構中將為它們提供這些方法。
type base struct{
data DatumType
}
func (b base) func1(){
}
func (b base) func2(){
}
func (b base) common_func(){
}
type derived1 struct {
base // anonymous meaning embedding
}
type derived2 struct {
base // anonymous meaning embedding
}
現在你可以這樣做:
d := derived1{}
d.func1()
d.func2()
d.common_func()
并且(正如 David Budworth 在評論中指出的那樣)您可以base通過引用它的類型名稱來訪問字段,如下所示:
d.base.data = something
- 2 回答
- 0 關注
- 184 瀏覽
添加回答
舉報