【问题标题】:Strange type definition syntax in Golang (name, then type, then string literal)Golang 中奇怪的类型定义语法(名称,然后是类型,然后是字符串文字)
【发布时间】:2012-07-13 14:59:45
【问题描述】:

我一直在尝试了解如何使用 mgo(Go 的 MongoDB 驱动程序),我遇到了这个结构声明:

type Something struct {
    Id bson.ObjectId "_id,omitempty"
    Name string
}

我不太了解第一个元素 (Id) 的语法。我知道它被声明为bson.ObjectId 类型,但是字符串文字在那里做什么?

我的问题不是关于 mgo 驱动程序的功能,
但是关于这个奇怪的<name> <type> <string_literal> 语法。

我在 Go 规范上找不到任何东西,我也不知道如何用谷歌搜索。

【问题讨论】:

标签: go


【解决方案1】:

language specificationStruct types 部分有解释:

字段声明后面可以跟一个可选的字符串字面量 tag,它成为对应字段声明中所有字段的属性。标签通过 reflection interface,否则会被忽略。

// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
    microsec  uint64 "field 1"
    serverIP6 uint64 "field 2"
    process   string "field 3"
}

【讨论】:

  • 具体来说,在mgo的情况下,标签会设置在将struct编码为bson时使用的key。这也是 encoding/json 包的工作方式。否则 Go 将使用 cap-initial 键。
猜你喜欢
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 2019-02-25
相关资源
最近更新 更多