在golang中,是否有可能获得反射。类型本身,从字符串名称? [英] In golang, is it possible to get reflect.Type from the type itself, from name as string?

查看:161
本文介绍了在golang中,是否有可能获得反射。类型本身,从字符串名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  type t1 struct {i int; s字符串} 
var v1 reflect.Type = / *如何设置为t1的reflect.Type? * /




  1. 有可能得到reflect.Type的t1没有实例化它?


  2. 是否有可能获得t1的reflect.Type从其名称t1作为字符串? $ / $>

    解决方案

    1,是,有点:

      var v1 reflect.Type = reflect.TypeOf((* t1)(nil))。Elem()
    fmt.Println(v1)//打印main.t1

    不需要实例化。但是,Go没有类型文字,我认为你在问什么。要获得某个类型的运行时值,您需要具有某种类型的值。如果你不想或者不能在运行时创建这个值,你可以从类型化的nil中取出它。如果你不喜欢每次都查看这个概念,你可以将这个运行时类型存储在一个变量中。



    2,不,不是。这将要求Go运行时维护当前二进制文件中所有类型的映射,其中有许多问题。您可以创建一个类型注册表包,并且可以通过字符串注册您想要检索的所有类型,但这样做总是不完整的,并且如果您知道需要什么类型,则始终可以使用TypeOf 。由于您可以拥有匿名类型,因此情况会变得更加复杂,像t1这样的名称并不一定是唯一的,因为另一个包可能具有相同名称的类型。 Go运行时可能会提供一个函数,它提供了一个字符串名称的类型,但我怀疑会发生。


    type t1 struct { i int; s string }
    var v1 reflect.Type = /* how to set to t1's reflect.Type? */
    

    1. is it possible to get the reflect.Type of t1 without having to instantiate it?

    2. is it possible to get the reflect.Type of t1 from having its name "t1" as a string?

    解决方案

    On 1, yes, kinda:

    var v1 reflect.Type = reflect.TypeOf((*t1)(nil)).Elem()
    fmt.Println(v1)  // prints "main.t1"
    

    No instantiation needed. However, Go doesn't have type literals, which is I think what you're asking for. To get the runtime value of a type, you need to have a value of some sort. If you don't want to or can't create the value at runtime, you can pull it from a typed nil. If you don't like the idea of looking this up every time, you can store this runtime type in a variable.

    On 2, no, not really. This would require the Go runtime to maintain a map of all types in the current binary, which has a number of problems. You could create a type registry package, and register all types you may want to retrieve by string, but that's always going to be incomplete, and if you know what type you want, you can always just use TypeOf. The situation is made a bit more complicated by the fact that you can have anonymous types, and the name like "t1" isn't certain to be unique, as another package may have a type of the same name. It is possible for the Go runtime to provide a function that gives a type from a string name, but I doubt that will happen.

    这篇关于在golang中,是否有可能获得反射。类型本身,从字符串名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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