doudeng1870 2014-04-14 10:10
浏览 667
已采纳

golang结构中tag的用途是什么?

I don't understand the significance of struct tags. I have been looking them, and noticed that they can be used with reflect package. But I don't know any practical uses of them.

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

3条回答 默认 最新

  • duanfu1873 2014-04-14 10:14
    关注

    The use of tags strongly depends on how your struct is used.

    A typical use is to add specifications or constraints for persistence or serialisation.

    For example, when using the JSON parser/encoder, tags are used to specify how the struct will be read from JSON or written in JSON, when the default encoding scheme (i.e. the name of the field) isn't to be used.

    Here are a few examples from the json package documentation :

    // 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"`
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助