“点括号”语法的含义是什么?

huangapple go评论99阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年6月30日 22:47:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/24492868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定