为什么我会在go lang中得到奇怪的类型断言结果?

为什么我会在go lang中得到奇怪的类型断言结果?,go,Go,此代码工作正常,但当我在一种情况下绑定它们时,例如: var i interface{} s := make([]map[string]interface{}, 5, 5) i = s switch x := i.(type) { case []interface{}: fmt.Println("type is an array") fmt.Println("length is: ") fmt.Pri

此代码工作正常,但当我在一种情况下绑定它们时,例如:

var i interface{}
s := make([]map[string]interface{}, 5, 5)
i = s
switch x := i.(type) {
    case []interface{}:
        fmt.Println("type is an array")
        fmt.Println("length is: ")
        fmt.Println(len(x))
    case []map[string]interface{}:
        fmt.Println("type is an array")
        fmt.Println("length is: ")
        fmt.Println(len(x))
  }
但是当我把它们绑定到一个case语句中时,它就不起作用了

switch x := i.(type) {
case []interface{}, []map[string]interface{}:
    fmt.Println("type is an array")
    fmt.Println("length is: ")
    fmt.Println(len(x))
}

请参阅语言规范:

TypeSwitchGuard可能包含一个简短的变量声明。使用该形式时,变量将在每个子句的隐式块中的TypeSwitchCase末尾声明。在只列出一种类型的case子句中,变量具有该类型;否则,变量具有TypeSwitchGuard中表达式的类型


另外,请记住Go是静态类型的。无法决定在运行时声明的变量的类型。因此,如果您列出多个类型,它只是使用与开关变量相同的类型声明变量。

唯一的问题是:

fmt.Println(len(x))

在第二个版本的运行时,Go不知道
x
[]接口{}
还是
[]映射[string]接口{}
,因此它只是一个
接口{}
。虽然底层类型是一个
[]
(某物),但此时
x
的实际类型只是
interface{}
,您不能在
interface{}
上调用
len
“不工作”不是一个问题描述。你好,Sharad。你能详细说明一下你的问题吗?我们需要更清楚地了解问题,以便适当地帮助您