为了账号安全,请及时绑定邮箱和手机立即绑定

类型开关的俱乐部值

类型开关的俱乐部值

Go
米琪卡哇伊 2022-12-05 16:46:12
以下代码工作正常var requestMap map[string]interface{}for _, value := range requestMap {    switch v := value.(type) {    case []interface{}:        if len(v) == 0 {            // if is empty then no need to throw NA            return http.StatusOK, nil        }    case string:        if len(v) == 0 {            // if is empty then no need to throw NA            return http.StatusOK, nil        }    }}但是下面的代码给出了invalid argument for len function,我已经阅读了这个问题var requestMap map[string]interface{}for _, value := range requestMap {    switch v := value.(type) {    case []interface{}, string:        if len(v) == 0 {            // if is empty then no need to throw NA            return http.StatusOK, nil        }    }}这个 case 语句不足以识别[]interface{}或string作为值类型吗?为什么它仍在考虑interface{}作为参数len()
查看完整描述

2 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

如果在case一个类型开关中列出多个类型,则switch变量的静态类型将是原始变量的类型。规范:开关语句:

在 case 中仅列出一种类型的子句中,变量具有该类型;否则,该变量具有 TypeSwitchGuard 中表达式的类型。

因此,如果 switch 表达式是v := value.(type)v则匹配案例(列出多种类型)中的 of 将是 的类型value,在您的情况下它将是interface{}。并且内置len()函数不允许传递 type 的值interface{}


查看完整回答
反对 回复 2022-12-05
?
holdtom

TA贡献1805条经验 获得超10个赞

这是因为在类型切换的情况下,v应同时转换为接口 ( )[]interface和 astring的一部分。编译器无法决定使用哪个,因此它会将值还原为,因为它可以是任何值。interface{}



查看完整回答
反对 回复 2022-12-05
  • 2 回答
  • 0 关注
  • 51 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信