Golang中能夠對struct
定義Tag
例如:git
type TestTag struct{
UserName string `json:"name"`
Age Int `json:"age"`
}
json:"name"
就是 UserName屬性的tag。 咱們能夠在反射中獲取Tag的內容。例如:json
if ctx,ok := reflect.Typeof(TestTag{}).Elem().FieldByName("UserName");ok{
fmt.Println(ctx.Tag)
}
Tag不只能夠當成註釋來使用,還能夠有更多使用地方。code
在解析json的時候能夠利用到Tag,例如:get
str :=`{"name":"test","age":18}`
temp:= []byte(str)
jsonObj :=new(TestTag)
err :=json.Unmarshal(temp,&jsonObj)
if err!=nil{
fmt.Println(err)
return
}
fmt.Println(temp.UserName)
這能夠經過tag的方式來進行對json解析。string