how to write a function to process two types of input data in golang

走远了吗. 提交于 2019-12-13 03:26:07

问题


I have multiple structs share some fields. For example,

type A struct {
    Color string
    Mass  float
    // ... other properties
}
type B struct {
    Color string
    Mass  float
    // ... other properties
}

I also have a function that only deals with the shared fields, say

func f(x){
    x.Color
    x.Mass
}

How to deal with such situations? I know we can turn the color and mass into functions, then we can use interface and pass that interface to the function f. But what if the types of A and B cannot be changed. Do I have to define two functions with essentially the same implementation?


回答1:


In Go you don't the traditional polymorphism like in Java, c#, etc. Most thing are done using composition and type embedding. A way of doing this simply is by changing your design and group the common field in a separate struct. It's just a different of thinking.

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)
}

There are other ways too by using interfaces and getters mentioned here but IMO this is the simplest way



来源:https://stackoverflow.com/questions/56588337/how-to-write-a-function-to-process-two-types-of-input-data-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!