“点括号"是什么意思?句法? [英] What is the meaning of "dot parenthesis" syntax?

查看:65
本文介绍了“点括号"是什么意思?句法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究在 mongodb 中存储数据的示例 Go 应用程序.这一行的代码(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{},括号之间是什么称为类型断言.它检查 sess.Values["user"] 的值是否属于 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

这篇关于“点括号"是什么意思?句法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆