Dynamic function return type

隐身守侯 提交于 2019-12-20 07:58:53

问题


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
}

回答1:


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)




回答2:


As noted in the comment - Go doesn't allow you to support generic return types. So you'd either want to return an interface type that you know your Entity types conform to or you'd return the empty interface type interface{}.



来源:https://stackoverflow.com/questions/52514540/dynamic-function-return-type

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