Reflection Golang反射:从结构字段获取标记

Reflection Golang反射:从结构字段获取标记,reflection,struct,go,Reflection,Struct,Go,是否可以对结构的字段进行反射,并获取对其标记值的引用 例如: type User struct { name string `json:name-field` age int } ... user := &User{"John Doe The Fourth", 20} getStructTag(user.name) ... func getStructTag(i interface{}) string{ //get tag from field }

是否可以对结构的字段进行反射,并获取对其标记值的引用

例如:

type User struct {
    name    string `json:name-field`
    age     int
}
...
user := &User{"John Doe The Fourth", 20}
getStructTag(user.name)
...
func getStructTag(i interface{}) string{
   //get tag from field

}

从我看到的情况来看,通常的方法是在typ.NumField()上设置范围,然后调用field.Tag.Get(“标记名”)。然而,在我的用例中,最好不必传入整个结构。有什么想法吗?

您不需要传入整个结构,但是传入其中一个字段的值是不够的

在您的示例中,
user.name
字段只是一个
字符串
——reflect包无法将其关联回原始结构

相反,您需要传递给定字段的
reflect.StructField

field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
…
tag = string(field.Tag)
注意:我们使用上面的
Elem
,因为
user
是指向结构的指针


您还可以按名称获取字段。传递结构有什么问题?如果您没有通过结构,您打算如何获得类型?您的游乐场示例有bug,我为那些不知道如何获得的人修复了这些bug: