Jam*_*meo 24 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
}
Run Code Online (Sandbox Code Playgroud)
从我所看到的,通常的方法是将范围超过typ.NumField(),然后调用field.Tag.Get("tagname").但是,在我的用例中,不必传递整个结构就好了.任何想法?
djd*_*djd 44
您不需要传入整个结构,但传递其中一个字段的值是不够的.在你的例子user.name中只是一个string- 反射包将无法将其与原始结构相关联.
相反,您需要传递reflect.StructField给定字段:
field, ok := reflect.TypeOf(user).Elem().FieldByName("name")
…
tag = string(field.Tag)
Run Code Online (Sandbox Code Playgroud)
见http://play.golang.org/p/G6wxUVVbOw
(注意,我们使用Elem上面因为user是指向结构的指针).
Raj*_*rma 10
修改上面的答案可以给出特定标签的值
package main
import (
"fmt"
"reflect"
)
type User struct {
Name string `json:"name_field"`
Age int
}
func main() {
user := &User{"John Doe The Fourth", 20}
field, ok := reflect.TypeOf(user).Elem().FieldByName("Name")
if !ok {
panic("Field not found")
}
fmt.Println(getStructTag(field, "json")) //name_field
}
func getStructTag(f reflect.StructField, tagName string) string {
return string(f.Tag.Get(tagName))
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/Sb0i7za5Uow