有没有办法从一个字符串创建一个结构的实例? [英] is there a way to create an instance of a struct from a string?
问题描述
pre $
type MyStruct struct {
A int
B int
}
和结构名称的字符串
a:=MyStruct
或
a:=mypkg.MyStruct
如何从字符串名称而不是结构体创建我的结构体实例?我的想法是,我将创建一个应用程序,其中包含链接到二进制文件中的所有结构,但是会从字符串中创建运行时实例。 (类的元元)
在Go中没有中央注册表类型,所以你问的是不可能的一般情况下。
您可以手动构建自己的注册表,以支持使用从字符串到 然后您可以创建类型的实例,如下所示: Given a struct: and a string with the struct's name or 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) 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 You can then create instances of the types like so:
这篇关于有没有办法从一个字符串创建一个结构的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! reflect.Type
值对应于每种类型。例如:
pre $ $ $ $ c $ var typeRegistry = make(map [string] reflect.Type)
func init (){
typeRegistry [MyString] = reflect.TypeOf(MyString {})
...
}
func makeInstance (name string)interface {} {
v:= reflect.New(typeRegistry [name]).elem()
//可能在这里填写字段
return v.Interface()
}
type MyStruct struct {
A int
B int
}
a := "MyStruct"
a := "mypkg.MyStruct"
reflect.Type
values corresponding to each type. For instance:var typeRegistry = make(map[string]reflect.Type)
func init() {
typeRegistry["MyString"] = reflect.TypeOf(MyString{})
...
}
func makeInstance(name string) interface{} {
v := reflect.New(typeRegistry[name]).Elem()
// Maybe fill in fields here if necessary
return v.Interface()
}