doujianglin6704 2014-04-12 13:17
浏览 18
已采纳

有没有一种方法可以从字符串创建结构实例?

Given a struct:

type MyStruct struct {
    A int
    B int
}

and a string with the struct's name

a := "MyStruct"

or

a := "mypkg.MyStruct"

How do I create an instance of my struct from the string name rather than the struct? The idea is that I would create an application with all of the structures linked into the binary but create the runtime instances from the strings. (sort of a meta-meta)

  • 写回答

3条回答 默认 最新

  • dongmacuo1193 2014-04-12 14:08
    关注

    There is no central registry of types in Go, so what you ask is impossible in the general case.

    You could build up your own registry by hand to support such a feature using a map from strings to reflect.Type values corresponding to each type. For instance:

    var typeRegistry = make(map[string]reflect.Type)
    
    func init() {
        myTypes := []interface{}{MyString{}}
        for _, v := range myTypes {
            // typeRegistry["MyString"] = reflect.TypeOf(MyString{})
            typeRegistry[fmt.Sprintf("%T", v)] = reflect.TypeOf(v)
        }
    }
    

    You can then create instances of the types like so:

    func makeInstance(name string) interface{} {
        v := reflect.New(typeRegistry[name]).Elem()
        // Maybe fill in fields here if necessary
        return v.Interface()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路