patterngoCritical
What is the meaning of "dot parenthesis" syntax?
Viewed 0 times
syntaxthemeaningparenthesiswhatdot
Problem
I am studying a sample Go 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:
Would someone please explain to me the syntax here? I understand that
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 in parentheses? Is this a function invocation?Solution
sess.Values["user"] is an interface{}, and what is between parenthesis is called a type assertion. It checks that the value of sess.Values["user"] is of type bson.ObjectId. If it is, then ok will be true. Otherwise, it will be false.For instance:
var i interface{}
i = int(42)
a, ok := i.(int)
// a == 42 and ok == true
b, ok := i.(string)
// b == "" (default value) and ok == falseCode Snippets
var i interface{}
i = int(42)
a, ok := i.(int)
// a == 42 and ok == true
b, ok := i.(string)
// b == "" (default value) and ok == falseContext
Stack Overflow Q#24492868, score: 162
Revisions (0)
No revisions yet.