113

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:

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?

0

1 Answer 1

152

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 == false
4
  • 12
    @akonsu, It worth mentioning that the idiom used for type assertion is known as "comma ok" (if value, ok := try_to_obtain_value(); ok { ...), and is explained, for instance, in "Effective Go" -- see the section called "Maps". I should add that this whole document is a must read for any wannabe gopher.
    – kostix
    Jun 30, 2014 at 15:54
  • 12
    also worth mentioning that while b, ok := i.(string) works like TryAssert, b := i.(string) immediately panics if assertion is invalid. Mar 23, 2018 at 8:16
  • thanks, what about this sess.Values["user"].(type) it returns the type, right?
    – tim
    Sep 10, 2020 at 21:34
  • To be honest, this is a somewhat useful answer, and the comment by @kostix about comma ok is helpful. But it doesn't develop the interface aspect as fully as the user's example does. I'll soon have the ability to do that myself but since this question is closed I'll leave it there. Jul 8, 2021 at 1:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.