struct的tag到底可以用來做什麼?

astaxie發表於2018-03-13

在 Go 的 spec 檔案裡面針對 tag 有一些介紹 https://golang.org/ref/spec#Struct_types

> 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. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored.

struct {
    x, y float64 ""  // an empty tag string is like an absent tag
    name string  "any string is permitted as a tag"
    _    [4]byte "ceci n'est pas un champ de structure"
}

// A struct corresponding to a TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers;
// they follow the convention outlined by the reflect package.
struct {
    microsec  uint64 `protobuf:"1"`
    serverIP6 uint64 `protobuf:"2"`
}

這個文字解釋其實很短,也沒有很詳細的介紹這個到底可以用來做什麼?大家知道這個 tag 到底可以用來做什麼?怎麼用?

更多原創文章乾貨分享,請關注公眾號
  • struct的tag到底可以用來做什麼?
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章