我试图从某个值中提取标记,这是一个结构。我能够得到结构的字段,但不能提取标记。我在这里做错什么了?我尝试过许多不同的方法(使用reflect.Type、接口{}等),但都失败了。
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)
}
}任何见解都是非常有价值的。
发布于 2022-04-29 20:56:27
当您调用reflect.TypeOf(f)时,您将得到f的类型,它已经是一个reflect.Value。
使用此Type()函数获取类型并对其进行字段检查:
func printStructTags(f reflect.Value) { // f is of struct type `human`
for i := 0; i < f.NumField(); i++ {
fmt.Printf("Tags are %s\n", f.Type().Field(i).Tag)
}
}但是,使用f.Type().Field(i).Tag.Get("anonymize")检查标记并获取其值更容易。通过这种方式,您可以直接获得赋值的值,例如,在您的情况下是true,如果标签不存在,则得到一个空字符串。
https://stackoverflow.com/questions/72058220
复制相似问题