如何在不实例化结构的情况下获取结构标签

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

How to get a struct tag without having to instantiate the struct

问题

  1. type User struct{
  2. Name string `json:"name"`
  3. }
  4. func main() {
  5. t := reflect.TypeOf(User{})
  6. }

可以在不实例化它的情况下捕获标签的值。例如,捕获标签"json"的值,而无需实例化User结构体。

英文:
  1. type User struct{
  2. Name string `json:"name"`
  3. }
  4. func main() {
  5. t := reflect.TypeOf(User{})
  6. }

It is possible to capture the tag's values ​​without instantiating it. For example capturing the value of the tag "json" without having to instantiate the User structure.

答案1

得分: 4

在几乎所有情况下,创建一个值并不是一个性能问题,但是你可以通过使用空指针值来避免创建一个值。

  1. t := reflect.TypeOf((*User)(nil)).Elem() // Elem "dereferences" the pointer type.

在这里使用指针模式的原因是这种语法适用于所有类型。特别是,它处理接口类型:

  1. type I interface{}
  2. // 一些开发者可能期望以下代码返回 I 的类型,但实际上它返回的是 nil。
  3. t := reflect.TypeOf(I(nil))
  4. // 使用指针模式可以返回 I 的类型。
  5. t = reflect.TypeOf((*I)(nil)).Elem()

指针语法对于所有类型都是相同的,与该类型的零值如何书写无关:

  1. t = reflect.TypeOf(User{})
  2. t = reflect.TypeOf(uint(0))
  3. t = reflect.TypeOf(myString(""))

使用 t = reflect.TypeOf((*T)(nil)).Elem(),其中 T 是任意类型:

  1. t = reflect.TypeOf((*User)(nil)).Elem()
  2. t = reflect.TypeOf((*uint)(nil)).Elem()
  3. t = reflect.TypeOf((*myString)(nil)).Elem()
英文:

Creating a value is not a performance issue in almost all scenarios, but you can avoid creating a value by using a nil pointer value.

  1. t := reflect.TypeOf((*User)(nil)).Elem() // Elem "dereferences" the pointer type.

The reason to use the pointer pattern shown here is that the one syntax works with every type. In particular, it handles interface types:

  1. type I interface{}
  2. // Naive developers might expect the following
  3. // to return the type for I, but it actually
  4. // returns nil.
  5. t := reflect.TypeOf(I(nil))
  6. // The pointer pattern returns the type for I.
  7. t = reflect.TypeOf((*I)(nil)).Elem()

The pointer syntax is the same for all types independent of how the zero value is written for the type:

  1. t = reflect.TypeOf(User{})
  2. t = reflect.TypeOf(uint(0))
  3. t = reflect.TypeOf(myString(""))

Use t = reflect.TypeOf((*T)(nil)).Elem() where T is any type:

  1. t = reflect.TypeOf((*User)(nil)).Elem()
  2. t = reflect.TypeOf((*uint)(nil)).Elem()
  3. t = reflect.TypeOf((*myString)(nil)).Elem()

huangapple
  • 本文由 发表于 2021年11月4日 09:13:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/69833462.html
匿名

发表评论

匿名网友

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

确定