Strange type definition syntax in Golang (name, then type, then string literal)

huangapple go评论116阅读模式
英文:

Strange type definition syntax in Golang (name, then type, then string literal)

问题

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

  1. type Something struct {
  2. Id bson.ObjectId "_id,omitempty"
  3. Name string
  4. }

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

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

我在Go规范中找不到任何相关信息,也不知道如何在谷歌上搜索这个。

英文:

I've been trying to find out how to use mgo (MongoDB driver for Go) and I came across this struct declaration:

  1. type Something struct {
  2. Id bson.ObjectId &quot;_id,omitempty&quot;
  3. Name string
  4. }

I don't quite understand the syntax of the first element (Id). I understand that it's being declared as type bson.ObjectId, but what is the string literal doing there?

My question is not about the mgo driver functionality,
but about this strange &lt;name&gt; &lt;type&gt; &lt;string_literal&gt; syntax.

I couldn't find anything on the Go specs, and I don't know how to google this either.

答案1

得分: 58

它在Struct types部分的language specification中有解释:

字段声明后面可以跟一个可选的字符串字面量tag,它成为相应字段声明中所有字段的属性。这些标签通过reflection interface可见,但在其他情况下被忽略。

  1. // 与TimeStamp协议缓冲区对应的结构体。
  2. // 标签字符串定义了协议缓冲区字段的编号。
  3. struct {
  4. microsec uint64 "field 1"
  5. serverIP6 uint64 "field 2"
  6. process string "field 3"
  7. }
英文:

It's explained in the Struct types section of the language specification:

> A field declaration may be followed by an optional string literal
> tag, which becomes an attribute for all the fields in the corresponding field declaration. The tags are made visible through a
> reflection interface but are otherwise ignored.

  1. // A struct corresponding to the TimeStamp protocol buffer.
  2. // The tag strings define the protocol buffer field numbers.
  3. struct {
  4. microsec uint64 &quot;field 1&quot;
  5. serverIP6 uint64 &quot;field 2&quot;
  6. process string &quot;field 3&quot;
  7. }

huangapple
  • 本文由 发表于 2012年7月14日 02:05:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/11475917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定