GoLang获取struct的tag内容, 这是tag,可以被reflect API访问;beego的ORM中也通过tag来定义参数的。
获取tag的内容是利用反射包来实现的。示例代码能清楚的看懂!
package main import ( "fmt" "reflect") type Job struct { AlarmStatus *string `json:"alarm_status" name:"alarm_status"` CPUTopology string `json:"cpu_topology" name:"cpu_topology"`} func main(){ a := "abc" s := Job{&a,"hello"} st := reflect.TypeOf(s) field := st.Field(1) fmt.Println(field.Tag.Get("json"), field.Tag.Get("name"))}
package mainimport ( "fmt" "reflect" // 这里引入reflect模块) type User struct { Name string "user name" //这引号里面的就是tag Passwd string "user passsword"} func main() { user := &User{"chronos", "pass"} s := reflect.TypeOf(user).Elem() //通过反射获取type定义 for i := 0; i < s.NumField(); i++ { fmt.Println(s.Field(i).Tag) //将tag输出出来 }}
package main import ( "fmt" "reflect") func main() { type S struct { F string `species:"gopher" color:"blue"` } s := S{} st := reflect.TypeOf(s) field := st.Field(0) fmt.Println(field.Tag.Get("color"), field.Tag.Get("species")) }
时间: 2024-10-05 08:47:39