我有多個struct共享一些字段。例如,type A struct { Color string Mass float // ... other properties}type B struct { Color string Mass float // ... other properties}我還有一個只處理共享字段的函數,比如說func f(x){ x.Color x.Mass}遇到此類情況如何處理?我知道我們可以將顏色和質量轉換為函數,然后我們可以使用接口并將該接口傳遞給函數f。A但是如果和的類型B無法更改怎么辦?我是否必須定義兩個具有基本相同實現的函數?
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
在 Go 中,您不需要像 Java、C# 等中那樣的傳統多態性。大多數事情都是使用組合和類型嵌入來完成的。實現此目的的一種簡單方法是更改設計并將公共字段分組到單獨的結構中。這只是思維方式不同而已。
type Common struct {
Color string
Mass float32
}
type A struct {
Common
// ... other properties
}
type B struct {
Common
// ... other properties
}
func f(x Common){
print(x.Color)
print(x.Mass)
}
//example calls
func main() {
f(Common{})
f(A{}.Common)
f(B{}.Common)
}
還有其他方法可以使用這里提到的接口和吸氣劑,但在我看來這是最簡單的方法
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消