如何在使用反射时设置标签

时间:2020-02-17 10:25:33

标签: pointers go struct go-reflect

从现有结构创建新结构时,不会在新结构上设置标签。

例如:

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
  Bar string `custom:"tag"`
}

func readTag(e interface{}) {
  t := reflect.TypeOf(e).Elem()
  f, _ := t.FieldByName("Bar")
  fmt.Println(f.Tag)
}

func main() {
  foo := &Foo{"baz"}

  fmt.Println(foo)
  readTag(foo)

  fooType := reflect.TypeOf(foo).Elem()
  newFoo := reflect.New(fooType).Elem()
  newFoo.FieldByName("Bar").SetString("baz2")
  fmt.Println(newFoo)
  readTag(&newFoo)// empty
}

游乐场链接:https://play.golang.org/p/7-zMPnwQ8Vo

如何在使用reflect.New时设置标签?可能吗

1 个答案:

答案 0 :(得分:4)

标签不属于实例,标签属于类型。

因此,当您创建自己的类型的新实例时,它们的类型将是相同的“穿着”相同的标记。使用文字或通过reflect包创建新实例都没关系。

您遇到的问题是newFoo的类型为reflect.Value,而&newFoo的类型为*reflect.Value,它不是指向您的结构的指针(不是类型的指针) *Foo

如果解开结构值:

newFoo.Interface()

然后您将其传递给Elem()调用(仅当它是指针时才这样做):

func readTag(e interface{}) {
    t := reflect.TypeOf(e)
    if t.Kind() == reflect.Ptr {
        t = t.Elem()
    }
    f, _ := t.FieldByName("Bar")
    fmt.Println(f.Tag)
}

然后您将获得相同的标记(在Go Playground上尝试):

&{baz}
custom:"tag"
{baz2}
custom:"tag"

如果保留reflect.Value包装结构指针,并对其进行解包,则会得到相同的结果:

newFooPtr := reflect.New(fooType)
newFoo := newFooPtr.Elem()
newFoo.FieldByName("Bar").SetString("baz2")
fmt.Println(newFoo)
readTag(newFooPtr.Interface()) // empty

然后readTag()不需要修改。在Go Playground上尝试此版本。