如何通过反射从名称中获取类型表示?
有没有办法在 Go 中使用 反射库 从类型的名称开始到它的 Type 表示?
Is there a way to use the reflection libraries in Go to go from the name of a type to its Type representation?
我有一个库,用户需要在其中为某些代码生成提供类型表示.我知道这一定是可能的(在某种意义上),因为他们可以创建一个该类型的变量并调用 TypeOf 函数,但是有没有办法绕过这个并从名称中获取表示?
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.
如果类型名称作为 string
值提供,那么在运行时这是不可能的,因为没有显式引用的类型可能不会被编译成最终的可执行二进制文件(因此显然变得无法访问, 运行时未知").有关详细信息,请参阅拆分客户端/服务器代码.有关可能的解决方法,请参阅 调用所有函数Golang 中的特殊前缀或后缀.
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.
如果我们谈论编码"时间(源代码编写/生成),那么无需创建/分配给定类型的变量并调用 reflect.TypeOf()
并传递变量.
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.
你可以从指针开始到类型,并使用一个类型化的nil
指针值而不分配,你可以从它的reflect.Type
描述符到base 的描述符 类型(或 element 类型)使用 Type.Elem()
的指针.
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()
.
这是它的样子:
t := reflect.TypeOf((*YourType)(nil)).Elem()
上面的类型描述符 t
将与下面的 t2
相同:
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)
上述应用程序的输出(在 Go Playground 上尝试):
Output of the above application (try it on the Go Playground):
main.YourType main.YourType
true