dream04110 2017-06-21 12:23
浏览 22

有没有一种方法可以使用地图和界面在Go中的不同包中转换结构?

I want to convert some struct types between different packages and then operate on the structs that are in my package without using if/else or switch statements. Is that possible to do using just maps and interfaces? I have some ideas in place for how I can do this.

Package Other

type Update interface{}

type FirstUpdate struct {
    x int
    y int
}

type SecondUpdate struct {
    z string
}

// these methods return different implementations of Update structs
FirstRequestConverter(events []string, topic string) Update
SecondRequestConverter(events []string, topic string) Update

Package Mine

type ConversionFunction func([]string, string) other.Update

type FirstUpdateConverted other.FirstUpdate
type SecondUpdateConverted other.SecondUpdate

type ServiceCaller interface {
    // includes relevant methods
}    

topicsMap := map[string]ConversionFunction{
    "first_topic": other.FirstRequestConverter,
    "second_topic": other.SecondRequestConverter,
}

conversionFunction = topicsMap[topic]
// need to convert other package types to alias types
...
updateConverted.callService()

Here, my map from string to ConversionFunction lets me pick the conversion function I want to use at runtime. And if both FirstUpdateConverted and SecondUpdateConverted implement the ServiceCaller interface, I can choose how the converted structure is handled at runtime too.

In order to convert from FirstUpdate to FirstUpdateConverted (or any of the other alias types), however, I need to use a switch and convert manually.

Is there another way to do the struct conversion step?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 无线电能传输系统MATLAB仿真问题
    • ¥50 如何用脚本实现输入法的热键设置
    • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
    • ¥30 深度学习,前后端连接
    • ¥15 孟德尔随机化结果不一致
    • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
    • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
    • ¥15 谁有desed数据集呀
    • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
    • ¥15 关于#hadoop#的问题