golang结构中标签的用途是什么?

use*_*973 4 go

我不明白struct标签的意义.我一直在寻找它们,并注意到它们可以与反射包一起使用.但我不知道它们的任何实际用途.

type TagType struct { // tags
    field1 bool   “An important answer”
    field2 string “The name of the thing”
    field3 int    “How much there are”
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 8

标签的使用在很大程度上取决于结构的使用方式.

典型用法是为持久性或序列化添加规范或约束.

例如,当使用JSON解析器/编码器时,标签用于指定在不使用默认编码方案(即字段的名称)时如何从JSON读取结构或用JSON编写结构.

以下是json包文档中的一些示例:

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`
Run Code Online (Sandbox Code Playgroud)