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

报告相同问题?