在golang中,是否可以从类型本身获取reflect.Type,从字符串名称获取?

huangapple go评论91阅读模式
英文:

In golang, is it possible to get reflect.Type from the type itself, from name as string?

问题

type t1 struct { i int; s string }
var v1 reflect.Type = reflect.TypeOf(t1{})

  1. 是否可以在不实例化t1的情况下获取其reflect.Type?

  2. 是否可以通过将其名称“t1”作为字符串来获取t1的reflect.Type?

英文:
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?

答案1

得分: 53

On 1, yes, kinda:

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

不需要实例化。然而,Go语言没有类型字面量,这可能是你所问的。要获取类型的运行时值,你需要有某种类型的值。如果你不想或者不能在运行时创建值,你可以从一个类型为nil的变量中获取它。如果你不喜欢每次都查找它的想法,你可以将这个运行时类型存储在一个变量中。

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.

英文:

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.

huangapple
  • 本文由 发表于 2011年6月18日 03:06:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/6390585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定