🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
Elem反射获取tag ~~~ package main import ( "fmt" "reflect" ) type Student struct { Name string `json:"stu_name"` Age int Score float32 } func TestStruct(a interface{}) { typ := reflect.TypeOf(a) tag := typ.Elem().Field(0).Tag.Get("json") fmt.Printf("Tag:%s\n", tag) } func main() { var a Student = Student{ Name: "stu01", Age: 18, Score: 92.8, } TestStruct(&a) } ~~~ 输出结果: ~~~ Tag:stu_name ~~~ 获取 tag(一) ~~~ package main import ( "fmt" "reflect" ) func main() { type User struct { Name string "user name" Passwd string `user passsword` } u := &User{ Name: "Murphy", Passwd: "123456", } s := reflect.TypeOf(u).Elem() for i := 0; i < s.NumField(); i++ { fmt.Println(s.Field(i).Tag) } } ~~~ 获取 tag(二) ~~~ package main import ( "fmt" "reflect" ) func main() { type User struct { Name string `json:"user_name" name:"user name"` } u := User{ Name: "Murphy", } f := reflect.TypeOf(u).Field(0) fmt.Println(f.Tag.Get("json")) fmt.Println(f.Tag.Get("name")) } ~~~