What is the meaning of “dot parenthesis” syntax in Golang?

拟墨画扇 提交于 2019-11-26 09:46:48

问题


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 an 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?


回答1:


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


来源:https://stackoverflow.com/questions/24492868/what-is-the-meaning-of-dot-parenthesis-syntax-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!