类型开关的俱乐部值
以下代码工作正常
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
}
}
}
,但是以下代码给出了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
}
}
}
此情况语句难道不够识别[]接口{}
或string
作为值类型? 为什么仍将接口{}
作为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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您在类型开关的
案例
中列出了多种类型,则switch> switch
变量的静态类型将是原始变量的类型。 spec:switch语句:因此,如果开关表达式为
v:= value。(type)
,在匹配案例中v
(列表多种类型)将是value的类型
,在您的情况下,它将是接口{}
。 andininlen()
函数不允许通过值传递值类型接口{}
。If you list multiple types in a
case
of a type switch, the static type of theswitch
variable will be of the type of the original variable. Spec: Switch statements:So if the switch expression is
v := value.(type)
, the ofv
in the matching case (listing multiple types) will be the type ofvalue
, in your case it will beinterface{}
. And the builtinlen()
function does not allow to pass values of typeinterface{}
.这是因为在类型开关的情况下,应将
v
转换为接口([]接口
)和String
在同时。编译器无法决定要使用哪个,因此它将值还原为接口{}
,因为它可以是任何东西。This is because in the case of the type switch, the
v
should be converted to a slice of interface ([]interface
) and to astring
at the same time. The compiler can't decide which to use, so it revert back the value tointerface{}
, since it can be anything.