加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:28:16 所属栏目:大数据 来源:网络整理
导读:我不明白struct标签的意义.我一直在寻找它们,并注意到它们可以与反射包一起使用.但我不知道它们的任何实际用途. type TagType struct { // tags field1 bool “An important answer” field2 string “The name of the thing” field3 int “How much there
我不明白struct标签的意义.我一直在寻找它们,并注意到它们可以与反射包一起使用.但我不知道它们的任何实际用途.

type TagType struct { // tags
    field1 bool   “An important answer”
    field2 string “The name of the thing”
    field3 int    “How much there are”
}

解决方法

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

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

例如,当使用JSON parser/encoder时,标签用于指定在不使用默认编码方案(即字段的名称)时如何从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"`

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读