我试图从一个 struct 的特定值中提取标记.我能够获取 struct 的字段,但无法提取标记.我做错了什么?我try 了许多不同的方法(使用reflect.Type、interface{}等),但都失败了.
type House struct {
Room string
Humans Human
}
type Human struct {
Name string `anonymize:"true"` // Unable to get this tag
Body string
Tail string `anonymize:"true"` // Unable to get this tag
}
func printStructTags(f reflect.Value) { // f is of struct type `human`
for i := 0; i < f.NumField(); i++ {
fmt.Printf("Tags are %s\n", reflect.TypeOf(f).Field(i).Tag) // TAGS AREN'T PRINTED
}
}
我之所以使用reflect.Value
作为参数,是因为这个函数是通过以下方式从另一个函数调用的
var payload interface{}
payload = &House{}
// Setup complete
v := reflect.ValueOf(payload).Elem()
for j := 0; j < v.NumField(); j++ { // Go through all fields of payload
f := v.Field(j)
if f.Kind().String() == "struct" {
printStructTags(f)
}
}
任何洞见都是极其宝贵的