Golang 中奇怪的类型定义语法(名称,然后类型,然后是字符串字面量) [英] Strange type definition syntax in Golang (name, then type, then string literal)
问题描述
我一直在试图找出如何使用 mgo(用于 Go 的 MongoDB 驱动程序),但我遇到了这个结构声明:
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
}
我不太明白第一个元素 (Id) 的语法.我知道它被声明为 bson.ObjectId
类型,但是字符串文字在那里做什么?
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?
我的问题不是关于 mgo 驱动程序的功能,
但是关于这个奇怪的
语法.
My question is not about the mgo driver functionality,
but about this strange <name> <type> <string_literal>
syntax.
我在 Go 规范上找不到任何内容,我也不知道如何在谷歌上搜索.
I couldn't find anything on the Go specs, and I don't know how to google this either.
推荐答案
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"
}
这篇关于Golang 中奇怪的类型定义语法(名称,然后类型,然后是字符串字面量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!