从现有结构创建新结构时,不会在新结构上设置标签。
例如:
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
时设置标签?可能吗
答案 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上尝试此版本。