实例新类型(Golang) [英] Instance new Type (Golang)

查看:124
本文介绍了实例新类型(Golang)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我如何从字符串中创建一个新的Type实例吗?反映?



有些例子,但它们是语言[:(]

)的较旧版本(前1版本)。

解决方案

所以,如果我正确理解你的问题,你就会问你如何创建一个对象,当你只有字符串类型的名称时,你可能有一个字符串MyStruct,你想创建一个这种类型的对象。



不幸的是,这不是一件容易的事,因为Go是一种静态类型的语言,链接器将消除死代码(或其内联部分),因此,不能保证您的最终可执行文件甚至会包含MyStruct代码。



您可以然而,手动维护一个全局的 map [string] reflect.Type 。例如,通过初始化 init()函数,它定义了这种发现类型,这也会告诉编译器你正在使用这些类型,之后你可以使用这个ma p查找要创建的类型的 reflect.Type 并使用 reflect.New 获取指向该类型的新对象(存储为reflect.Value)的指针。您可以将对象提取到类似如下的接口中:

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

Elem()将取消引用指针和 Interface()会将返回的值作为 interface {} 返回。有关详细信息,请参见反思法则



PS:可能有更好的方法来构建你的程序,它甚至不需要反射,也不会让编译器捕获更多的错误。例如,您是否考虑过使用工厂方法?另一个简单的解决方案可能是维护一个 map [string] func()接口{} 函数,这些函数可以被调用以创建一个具有该名称的新对象。

Can anyone tell me how to create a new instance of Type from a string? Reflect?

There are examples but they are for the older (pre Go 1 versions) of the language [:(]

解决方案

So, if I understand your question correctly, you are asking about how you can create an object when you just have the name of the type as string. So, for example, you might have a string "MyStruct" and you want to create an object of this type.

Unfortunately, that's not easily possible because Go is a statically typed language and the linker will eliminate dead code (or inline parts of it). So, there is no guarantee, that your final executable will even contain the code of "MyStruct".

You can however, maintain a global map[string]reflect.Type manually. For example by initializing this map in the init() function of your packages which defines such discover-able types. This will also tell the compiler that you are using the types. Afterwards, you can use this map to look up the reflect.Type of the type you want to create and use reflect.New to get a pointer to a new object of that type (stored as a reflect.Value). You can extract the object into an interface with something like this:

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

Elem() will de-reference the pointer and Interface() will return the reflected value as an interface{}. See The Laws of Reflection for further details.

PS: There might be a better way to structure your program which doesn't even require reflection and which let the compiler catch more errors. Have you considered using a factory method for example? An other easy solution might be to maintain a map[string]func() interface{} of functions which can be invoked to create a new object with that name.

这篇关于实例新类型(Golang)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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