问题描述

是否可以在结构的某个字段上进行反思,并获得对其标记值的引用?

Is it possible to reflect on a field of a struct, and get a reference to its tag values?

例如:

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").但是,在我的用例中,最好不必传递整个结构.有什么想法吗?

From what I can see, the usual way to do this is to range over typ.NumField(), and then call field.Tag.Get("tagname"). However, in my use-case, it would be much better to not have to pass the whole struct in. Any ideas?

推荐答案

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

You don't need to pass in the whole struct, but passing in the value of one of the fields is not sufficient.

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

这篇关于Golang反射:从结构字段获取标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!