Search code examples
gopolymorphism

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


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?


Solution

  • In Go you don't the traditional polymorphism like in Java, c#, etc. Most things 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