golang-Tag

Tag

理解

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

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息