Home > Net >  Why is this type assertion from bson.M necessary?
Why is this type assertion from bson.M necessary?

Time:06-17

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{})

CodePudding user response:

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

Runnable example in Go playground.

  • Related