doukuipei9938 2019-06-13 20:45
浏览 69
已采纳

如何在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?

  • 写回答

1条回答 默认 最新

  • douzhong4222 2019-06-13 21:12
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序