英文:
What is the type of this literal?
问题
从mgo
文档中:
pipe := collection.Pipe([]bson.M{{"$match": bson.M{"name": "Otavio"}}})
分解这个语句,我看到传递给collection.Pipe
的参数的类型是[]bson.M
。鉴于切片是通过[]sometype{ ... }
语法进行初始化的,我得出结论,上述切片只包含一个项(所以len == 1
),而这个项就是{"$match": bson.M{"name": "Otavio"}}
字面量。
这个字面量的类型是什么?直觉上,我想说它是一个map[string]interface{}
,但是当我在Go Playground上尝试检查时,我无法初始化类似的数据结构:https://play.golang.org/p/7QKYaQPi6g
因此,我的问题有两个:
https://play.golang.org/p/7QKYaQPi6g
的类型是什么(假设我在推理中没有犯错)。- 在
x := {"foo": 1, "bar": 1}
中我做错了什么?
英文:
From the mgo
docs:
pipe := collection.Pipe([]bson.M{{"$match": bson.M{"name": "Otavio"}}})
Decomposing this statement, I see that the argument passed to collection.Pipe
is of type []bson.M
. Given that slices are initialized via []sometype{ ... }
syntax, I conclude that the aforementioned slice contains exactly one item (so len == 1
), and that this item is the {"$match": bson.M{"name": "Otavio"}}
literal.
What is the type of this literal? Intuitively, I want to say it's a map[string]interface{}
, but when I tried checking on the go playground, I'm unable to initialize a similar data structure: https://play.golang.org/p/7QKYaQPi6g
My question is therefore twofold:
- What is the type of
https://play.golang.org/p/7QKYaQPi6g
(assuming I've made no mistake in my reasoning) - What am I doing wrong in
x := {"foo": 1, "bar": 1}
?
答案1
得分: 2
bson.M
只是map[string]interface{}
的另一个名称。请参阅其文档。它声明为:
type M map[string]interface{}
所以,是的,{"$match": bson.M{"name": "Otavio"}
是bson.M
类型的。
英文:
bson.M
is just another name for map[string]interface{}
. See its documentation. Its declared as,
type M map[string]interface{}
So, yes {"$match": bson.M{"name": "Otavio"}
is of type bson.M
答案2
得分: 1
x := {"foo": 1, "bar": 1}
在这个语句中,没有机会推断类型。当你像这样做时:
[]bson.M{{"$match": bson.M{"name": "Otavio"}}}
编译器知道你正在初始化特定类型的切片,所以没有必要每次都重复这个类型(除非它是接口)。这种初始化被称为复合字面量,并在go1.0中引入。
英文:
x := {"foo": 1, "bar": 1}
In this statement there is no chance to deduct the type. When you do something like this:
[]bson.M{{"$match": bson.M{"name": "Otavio"}}}
Compiler know that you are initializing slice of specific type, so there is no need to repeat this type every time (unless it's interface). This initalisation is called composite literals and was introduced in go1.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论