• 隐藏侧边栏
  • 展开分类目录
  • 关注微信公众号
  • 我的GitHub
  • QQ:1753970025
Chen Jiehua

Go struct tags 

关于Go中的Struct tags,http://golang.org/ref/spec中对它的描述:

A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
    microsec  uint64 "field 1"
    serverIP6 uint64 "field 2"
    process   string "field 3"
}

http://golang.org/pkg/reflect/#StructField中的描述:

type StructTag string

A StructTag is the tag string in a struct field.

By convention, tag strings are a concatenation of optionally space-separated key:”value” pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ‘ ‘), quote (U+0022 ‘”‘), and colon (U+003A ‘:’). Each value is quoted using U+0022 ‘”‘ characters and Go string literal syntax.

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"))
}

因此,对于 encoding/json ,我们可以这样使用:

type Person struct {
    FirstName    string    json:"first_name"
    LastName     string    json:"last_name"
    MiddleName   string    json:"middle_name,omitempty"
}
func main() {
    json_string := 
    {
        "first_name": "John",
        "last_name": "Smith"
    }

    person := new(Person)
    json.Unmarshal([]byte(json_string), person)
    fmt.Println(person)

    new_json, _ := json.Marshal(person)
    fmt.Printf("%sn", new_json)
}

参考:

http://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go
http://golang.org/pkg/reflect/#StructTag

码字很辛苦,转载请注明来自ChenJiehua《Go struct tags》

评论