Golang反射:从结构字段获取标签 [英] Golang Reflection: Get Tag from struct field
问题描述
是否可以在结构的某个字段上进行反思,并获得对其标记值的引用?
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
-反射包将无法将其与原始结构相关联.
In your example user.name
field is just a string
- the reflect package will have no way of correlating that back to the original struct.
相反,您需要传递给定字段的 reflect.StructField
:
Instead, you need to pass around the reflect.StructField
for the given field:
field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
…
tag = string(field.Tag)
注意:我们使用上面的 Elem
,因为 user
是指向结构的指针.
Note: we use Elem
above because user
is a pointer to a struct.
这篇关于Golang反射:从结构字段获取标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!