如何在Golang中编写函数来处理两种类型的输入数据
我有多个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
}
如何处理这种情况?我知道我们可以将颜色和质量转换为函数,然后可以使用interface并将该接口传递给function
f
。但是,如果不能更改A
和的类型,该怎么办B
。我是否必须定义两个具有基本相同实现的功能?
-
在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) }
使用此处)提到的接口和获取器也有其他方法,但是IMO这是最简单的方法