douque8861 2015-05-07 10:36
浏览 25
已采纳

如何在go地图中存储类型以便以后进行初始化

I'm trying to implement a factory function that will return an instance of one of many structs that fulfil the contract of an interface X.

m := make(map[string] ?)
func init () {
    m["a"] = ?
    m["b"] = ?
}

type X interface { 
    y()
}

type A struct {}
func (a * A) y () {}

type B struct {}
func (b * B) y () {}


function factory(name string) X {
    return &m[name]{}
}

The code above is just a simplified demonstration of what I'm trying to achieve - looking for pointers for whether this is possible, or if there is a different go idiom to solve this kind of requirement that I'm missing.

  • 写回答

2条回答 默认 最新

  • dousi3362 2015-05-07 10:54
    关注

    You can use map[string]X, with X the interface (which can reference a value or a pointer of any object respecting X contract)

    or if there is a different go idiom to solve this kind of requirement that I'm missing?

    You can also use reflection (as in "Instance new Type") to implement your factory.

    reflect.New(yourtype).Elem().Interface()
    

    You can see a factory example in "is there a way to create an instance of a struct from a string?".


    The quicker approach for a factory method (returning a new instance each time) is using a switch (like in this example):

    // Create a new Widget interface based on WidgetType and set WidgetInfo
    func New(wt WidgetType, wi WidgetInfo) Widget_iface {
        switch wt {
        case Widget_A:
            return newWidgetA(wi)
        case Widget_B:
            return newWidgetB(wi)
        }
        return nil
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题