go的struct的tag反射
点击查看代码
package main
import (
"encoding/json"
"fmt"
"reflect" // 这里引入reflect模块
)
func testTag1(){
type A struct {
B string `tag1:"b" tag2:"B" tag3:"d"` //这引号里面的就是tag
C string `tag1:"c" tag2:"C"`
}
user := &A{"fmt", "reflect"}
fmt.Printf("这是>>user=%v\n",user)
s := reflect.TypeOf(user).Elem() //通过反射获取type定义
fmt.Printf("这是>>s=%v 长度:%d\n",s,s.NumField())
for i := 0; i < s.NumField(); i++ {
fmt.Println("将tag输出出来>>",s.Field(i).Tag) //将tag输出出来
fmt.Println("tag2>>",s.Field(i).Tag.Get("tag2")) //将tag输出出来
fmt.Println("tag3>>",s.Field(i).Tag.Get("tag3")) //将tag输出出来
}
}
func testTag2(){
type S struct {
F string `species:"gopher" color:"blue"`
}
s1 := S{}
st := reflect.TypeOf(s1)
field := st.Field(0)
fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
}
func testTag3(){
type User struct {
UserId int `json:"user_id" bson:"user_id"`
UserName string `json:"user_name" bson:"user_name"`
}
// 输出json格式
u := &User{UserId: 1, UserName: "tony"}
j, _ := json.Marshal(u)
fmt.Println(string(j))
// 输出内容:{"user_id":1,"user_name":"tony"}
// 获取tag中的内容
t := reflect.TypeOf(u)
field := t.Elem().Field(0)
fmt.Println(field.Tag.Get("json"))
// 输出:user_id
fmt.Println(field.Tag.Get("bson"))
// 输出:user_id
}
func main() {
//testTag1()
//testTag2()
testTag3()
}
testTag3()输出:
点击查看代码
{"user_id":1,"user_name":"tony"}
user_id
user_id
testTag1()和testTag2()输出:
点击查看代码
这是>>user=&{fmt reflect}
这是>>s=main.A 长度:2
将tag输出出来>> tag1:"b" tag2:"B" tag3:"d"
tag2>> B
tag3>> d
将tag输出出来>> tag1:"c" tag2:"C"
tag2>> C
tag3>>
blue gopher
写入自己的博客中才能记得长久