Page tree
Skip to end of metadata
Go to start of metadata

Introduction

关于Go中的Struct tags,官方对它的描述:

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”
}

另外还有这样的描述:

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.

Example

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("%s\n", new_json)
}


  • No labels
Write a comment...