dongshi1215 2018-09-26 09:35
浏览 522
已采纳

Golang动态函数返回类型

I have an app separated on modules. There are several Entities and CSV module. Csv module supports only struct(Entity), but i want to make CSV module works with any type of entity. Now it works like this: Csv module receives data from channel and strictly converts it to EverySize struct. How can I achieve dynamical return type, so it will works with any type of Entity, not only with Everysize

    func prepareWrapData(data []feed.WrapExporterChannels) []everysize.EverySizeItem {
        var result []everysize.EverySizeItem
        for _, value := range data {
            result = append(result, *value.EverySizeItem)
        }
    return result
}
  • 写回答

2条回答 默认 最新

  • dtkmejg127475 2018-09-26 16:55
    关注

    Quick/Dirty solution: Return interface{}, but then you end up cheating the compiler, and the pain to do type checking is on you.

    Better/Safer solution: Think of the common operations you need to do on the types that you return, define those common methods on each type, and keep those common methods in an interface. If you are trying to return multiple types from a function, most probably there must already be some common relationship among them, or can be found with little restructuring. Return that interface from the function. This way, the compiler will always be able to check that you aren't returning something unexpected(something that doesn't implement those methods). You may want to look up how the factory method pattern is implemented in Golang. (Hint: It returns interfaces, and not a super class the way it's normally done in C++/Java)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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