英文:
Clubbing values of type switch
问题
以下是翻译好的内容:
以下代码运行正常:
var requestMap map[string]interface{}
for _, value := range requestMap {
switch v := value.(type) {
case []interface{}:
if len(v) == 0 {
// 如果为空,则不需要抛出 NA
return http.StatusOK, nil
}
case string:
if len(v) == 0 {
// 如果为空,则不需要抛出 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 {
// 如果为空,则不需要抛出 NA
return http.StatusOK, nil
}
}
}
这个 case 语句不足以识别 []interface{} 或 string 作为值类型吗?为什么它仍然将 interface{} 视为 len() 的参数?
英文:
Following code is working fine
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
}
}
}
But following code is giving invalid argument for len function, I have read this question
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
}
}
}
Isn't this case statement enough to identify []interface{} or string as value type ?
Why is it still considering interface{} as parameter of len()
答案1
得分: 2
这是因为在类型切换的情况下,v 应该同时转换为接口切片([]interface)和字符串(string)。编译器无法决定使用哪个类型,所以它将值恢复为 interface{},因为它可以是任何类型。
英文:
This is because in the case of the type switch, the v should be converted to a slice of interface ([]interface) and to a string at the same time. The compiler can't decide which to use, so it revert back the value to interface{}, since it can be anything.
答案2
得分: 2
如果在类型开关的case中列出多个类型,switch变量的静态类型将是原始变量的类型。规范:Switch语句:
> 在列出仅有一个类型的case子句中,变量具有该类型;否则,变量具有TypeSwitchGuard中表达式的类型。
因此,如果switch表达式是v := value.(type),在匹配的case中(列出多个类型),v的类型将是value的类型,在你的情况下将是interface{}。而内置的len()函数不允许传递interface{}类型的值。
英文:
If you list multiple types in a case of a type switch, the static type of the switch variable will be of the type of the original variable. Spec: Switch statements:
> In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard.
So if the switch expression is v := value.(type), the of v in the matching case (listing multiple types) will be the type of value, in your case it will be interface{}. And the builtin len() function does not allow to pass values of type interface{}.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论