ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
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")) } ~~~