英文:
What is the meaning of "dot parenthesis" syntax?
问题
这段代码是一个Go应用程序,它将数据存储在mongodb中。在这行代码(https://github.com/zeebo/gostbook/blob/master/context.go#L36)中,它似乎访问了存储在gorilla session中的用户ID:
if uid, ok := sess.Values["user"].(bson.ObjectId); ok {
...
}
请问有人可以解释一下这里的语法吗?我知道sess.Values["user"]
从session中获取一个值,但是后面的部分是什么意思?为什么点号后面的表达式要用括号括起来?这是一个函数调用吗?
英文:
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?
答案1
得分: 145
sess.Values["user"]
是一个 interface{}
,括号中的内容被称为 类型断言。它检查 sess.Values["user"]
的值是否为 bson.ObjectId
类型。如果是,ok
将为 true
。否则,将为 false
。
例如:
var i interface{}
i = int(42)
a, ok := i.(int)
// a == 42,ok == true
b, ok := i.(string)
// b == ""(默认值),ok == 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
.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论