英文:
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 "_id,omitempty"
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 <name> <type> <string_literal>
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 "field 1"
serverIP6 uint64 "field 2"
process string "field 3"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论