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

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

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

问题

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

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

我不太理解第一个元素(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:

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

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可见,但在其他情况下被忽略。

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

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.

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

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:

确定