[英]What is the use of tag in golang struct?
我不了解struct标签的重要性。 我一直在寻找它们,并注意到它们可以与反射包一起使用。 但是我不知道它们的任何实际用途。
type TagType struct { // tags
field1 bool “An important answer”
field2 string “The name of the thing”
field3 int “How much there are”
}
标签的使用在很大程度上取决于结构的使用方式。
典型用途是为持久性或序列化添加规范或约束。
例如,当使用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"`
使用的例子是JSON编码/解码中encoding/json
:
type TagType struct {
field1 bool `json:"fieldName"`
field2 string `json:",omitempty"`
}
文档中的更多详细信息: encoding / json
您还可以使用XML结构标签,如下所示
type SearchResult struct {
Title string `xml:"title,attr"`
Author string `xml:"author,attr"`
Year string `xml:"hyr,attr"`
ID string `xml:"owi,attr"`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.