“圆括号"的含义是什么? Golang中的语法? [英] What is the meaning of "dot parenthesis" syntax in Golang?
问题描述
我正在研究一个示例Go应用程序,该应用程序将数据存储在mongodb中.此行的代码( https://github.com/zeebo/gostbook/blob/master/context.go#L36 )似乎正在访问存储在大猩猩会话中的用户ID:
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 {
...
}
有人可以在这里给我解释一下语法吗?我知道sess.Values["user"]
从会话中获取值,但是接下来的部分是什么呢?为什么括号中的点后面是表达式?这是函数调用吗?
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?
推荐答案
sess.Values["user"]
是interface{}
,括号之间的内容称为 的值是否为bson.ObjectId
类型.如果是,则ok
将是true
.否则,它将为false
.
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
.
例如:
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
这篇关于“圆括号"的含义是什么? Golang中的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!