Golang反映:从名称获取类型表示? [英] Golang reflect: Get Type representation from name?

查看:163
本文介绍了Golang反映:从名称获取类型表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Go中使用反射库以从名称请输入 Type 表示法?



我有一个库,用户需要为某些代码生成提供类型表示。我知道这一定是可能的(从某种意义上说),因为他们可以创建一个这种类型的变量,然后调用 TypeOf函数,但有没有办法绕过这一点,只是从名称的表示形式?

解决方案

问题不是很明确,可以用两种方式来解释,其中一种答案是否定的,不可能的;而另一个答案是肯定的,这是可能的。



在运行时



如果类型名称是作为字符串值提供,那么在运行时就不可能,因为没有明确引用的类型可能不会被编译到最终的可执行二进制文件中(因此显然变得无法访问,未知在运行时)。有关详细信息,请参阅拆分客户端/服务器代码。有关可能的解决方法,请参阅调用所有函数特殊的前缀或后缀



在编码时间



如果我们谈论编码时间(源代码编写/生成),那么可以不创建/分配给定类型的变量并调用 reflect.TypeOf() 并传递变量。 指针开始到类型,并且使用类型化的 nil 指针值,而不用分配,并且您可以从它的 reflect.Type 描述符使用 Type.Elem()的指针的 base 类型(或元素类型)的描述符。 p>

这是它的样子:

  t:= reflect.TypeOf((YourType)( n))。Elem()

类型描述符 t t2 一样:

  var x YourType 
t2:= reflect.TypeOf(x)

fmt.Println(t,t2)
fmt.Println(t == t2)

上述应用程序的输出(在

  main.YourType main.YourType 


Is there a way to use the reflection libraries in Go to go from the name of a type to its Type representation?

I've got a library where the user needs to provide Type representations for some code generation. I know it must be possible (in a sense) because they can just create a variable of that type and call the TypeOf function, but is there a way to circumvent this and just get representation from the name?

解决方案

The question is not quite explicit, it can be interpreted in 2 ways, to one of which the answer is no, not possible; and the other to which the answer is yes, it's possible.

At runtime

If the type name is provided as a string value, then at runtime it's not possible as types that are not referred to explicitly may not get compiled into the final executable binary (and thus obviously become unreachable, "unknown" at runtime). For details see Splitting client/server code. For possible workarounds see Call all functions with special prefix or suffix in Golang.

At "coding" time

If we're talking about "coding" time (source code writing / generating), then it's possible without creating / allocating a variable of the given type and calling reflect.TypeOf() and passing the variable.

You may start from the pointer to the type, and use a typed nil pointer value without allocation, and you can navigate from its reflect.Type descriptor to the descriptor of the base type (or element type) of the pointer using Type.Elem().

This is how it looks like:

t := reflect.TypeOf((*YourType)(nil)).Elem()

The type descriptor t above will be identical to t2 below:

var x YourType
t2 := reflect.TypeOf(x)

fmt.Println(t, t2)
fmt.Println(t == t2)

Output of the above application (try it on the Go Playground):

main.YourType main.YourType
true

这篇关于Golang反映:从名称获取类型表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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