Golang Reflection:从struct字段获取标签

时间:2014-05-07 01:06:16

标签: 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

}

从我所看到的,通常的方法是将范围超过typ.NumField(),然后调用field.Tag.Get(“tagname”)。但是,在我的用例中,不必传递整个结构就好了。任何想法?

1 个答案:

答案 0 :(得分:42)

您不需要传入整个结构,但传递其中一个字段的值是不够的。在您的示例中,user.name只是string - 反射包无法将其与原始结构相关联。

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

field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
…
tag = string(field.Tag)

请参阅http://play.golang.org/p/G6wxUVVbOw

(注意,我们使用上面的Elem因为user是指向结构的指针。)

相关问题