有没有办法从字符串创建结构的实例? [英] is there a way to create an instance of a struct from a string?

查看:26
本文介绍了有没有办法从字符串创建结构的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个结构:

type MyStruct struct {
    A int
    B int
}

和一个带有结构名称的字符串

and a string with the struct's name

a := "MyStruct"

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)

推荐答案

Go 中没有类型的中央注册表,所以在一般情况下你问的是不可能的.

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

您可以使用从字符串到对应于每种类型的 reflect.Type 值的映射,手动构建自己的注册表以支持此类功能.例如:

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()
}

这篇关于有没有办法从字符串创建结构的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆