英文:
Why is this type assertion from bson.M necessary?
问题
我有以下代码,使用了go.mongodb.org/mongo-driver库:
updateMap := bson.M{
"$set": bson.M{
"dateAdded": primitive.NewDateTimeFromTime(time.Now()),
},
}
if len(alias) > 0 {
// 我不明白为什么需要这个类型断言
updateMap["$set"].(map[string]interface{})["alias"] = alias
}
如果我这样写:
updateMap["$addFields"].(map[string]map[string]string)["alias"] = alias
它无法编译通过。编译器已经知道updateMap的类型是bson.M,它是一个map[string]interface{}
。那么为什么要断言它真的是一个map[string]interface{}
对编译器有用呢?我以为它想知道它实际上是什么类型的接口,但显然它不希望我这样做。
这里发生了什么?
编辑:当然,需要注意的是,如果没有类型断言,它无法编译通过:
invalid operation: cannot index updateMap["$addFields"] (map index expression of type interface{})
英文:
I have the following code, making use of go.mongodb.org/mongo-driver libraries:
updateMap := bson.M{
"$set": bson.M{
"dateAdded": primitive.NewDateTimeFromTime(time.Now()),
},
}
if len(alias) > 0 {
// I don't see how this type assertion is necessary
updateMap["$set"].(map[string]interface{})["alias"] = alias
}
If I do:
updateMap["$addFields"].(map[string]map[string]string)["alias"] = alias
it doesn't compile. The compiler already knows that updateMap is of type bson.M which is a map[string]interface{}
. How does asserting that it really is a map[string]interface{}
doing anything useful for the compiler? I thought it would want to know what kind of interface it actually is, but apparently it doesn't want me to do that.
What is going on here?
edit: and of course, it should be noted that without a type assertion here, it doesn't compile:
> invalid operation: cannot index updateMap["$addFields"] (map index expression of type interface{})
答案1
得分: 1
bson.M
被定义为primitive.M
的别名,而primitive.M
被定义为type M map[string]interface{}
(即非别名类型)。问题在于updateMap["$set"]
是一个bson.M
,与map[string]interface{}
相比是一个不同的类型。因此,你的类型断言应该是bson.M
,例如:
updateMap["$set"].(bson.M)["alias"] = alias
英文:
bson.M
is defined as an alias of primitive.M
, which is defined as type M map[string]interface{}
(that is, a non-alias type). The problem is that updateMap["$set"]
is a bson.M
, which is a distinct type compared to map[string]interface{}
. So your type assertion would have to be to bson.M
instead, for example:
updateMap["$set"].(bson.M)["alias"] = alias
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论