I am studying a sample golang application that stores data in mongodb. The code at this line (https://github.com/zeebo/gostbook/blob/master/context.go#L36) seems to access a user ID stored in a gorilla session:
if uid, ok := sess.Values["user"].(bson.ObjectId); ok {
...
}
Would someone please explain to me the syntax here? I understand that sess.Values["user"]
gets a value from the session, but what is the part that follows? Why is the expression after the dot is in parentheses? Is this a function invocation? Thanks!
sess.Values["user"]
is aninterface{}
, and what is between parenthesis is called a type assertion. It checks that the value ofsess.Values["user"]
is of typebson.ObjectId
. If it is, thenok
will betrue
. Otherwise, it will befalse
.For instance:
That's simply a type assertion.