这个字面量的类型是什么?

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

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

因此,我的问题有两个:

  1. https://play.golang.org/p/7QKYaQPi6g的类型是什么(假设我在推理中没有犯错)。
  2. 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:

  1. What is the type of https://play.golang.org/p/7QKYaQPi6g (assuming I've made no mistake in my reasoning)
  2. 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

huangapple
  • 本文由 发表于 2016年4月5日 22:00:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/36428562.html
匿名

发表评论

匿名网友

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

确定