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

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

问题描述

给定一个结构体:

pre $ type MyStruct struct {
A int
B int
}

和结构名称的字符串

  a:=MyStruct



  a:=mypkg.MyStruct

如何从字符串名称而不是结构体创建我的结构体实例?我的想法是,我将创建一个应用程序,其中包含链接到二进制文件中的所有结构,但是会从字符串中创建运行时实例。 (类的元元)

解决方案

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

您可以手动构建自己的注册表,以支持使用从字符串到 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()
}


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)

解决方案

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() {
    typeRegistry["MyString"] = reflect.TypeOf(MyString{})
    ...
}

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天全站免登陆