类型开关的俱乐部值

以下代码工作正常


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()


米琪卡哇伊
浏览 55回答 2
2回答

斯蒂芬大帝

如果在case一个类型开关中列出多个类型,则switch变量的静态类型将是原始变量的类型。规范:开关语句:在 case 中仅列出一种类型的子句中,变量具有该类型;否则,该变量具有 TypeSwitchGuard 中表达式的类型。因此,如果 switch 表达式是v := value.(type),v则匹配案例(列出多种类型)中的 of 将是 的类型value,在您的情况下它将是interface{}。并且内置len()函数不允许传递 type 的值interface{}。

holdtom

这是因为在类型切换的情况下,v应同时转换为接口 ( )[]interface和 astring的一部分。编译器无法决定使用哪个,因此它会将值还原为,因为它可以是任何值。interface{}
打开App,查看更多内容
随时随地看视频慕课网APP