如何将interface {}转换为[] int?

如何将interface {}转换为[] int?

问题描述:

我在用Go语言进行编程。

假设有一个interface{}的变量,其中包含一个整数数组。我该如何将interface {}转换为[] int?

我试过 interface_variable,但出错了:

panic: interface conversion: interface is []interface {}, not []int

我正在使用Go编程语言进行编程。 p>

说有一个变量 键入 interface {} code>,其中包含一个整数数组。 如何将 interface {} code>转换回 [] int code>? p>

我尝试过 p> interface_variable。([] int) code> pre>

我得到的错误是: p>

  panic  :接口转换:接口是[]接口{},而不是[] int 
  code>  pre> 
  div>

It's a []interface{} not just one interface{}, you have to loop through it and convert it:

http://play.golang.org/p/R441h4fVMw

func main() {
    a := []interface{}{1, 2, 3, 4, 5}
    b := make([]int, len(a))
    for i := range a {
        b[i] = a[i].(int)
    }
    fmt.Println(a, b)
}

As others have said, you should iterate the slice and convert the objects one by one. Is better to use a type switch inside the range in order to avoid panics:

a := []interface{}{1, 2, 3, 4, 5}
b := make([]int, len(a))
for i, value := range a {
    switch typedValue := value.(type) {
    case int:
        b[i] = typedValue
        break
    default:
        fmt.Println("Not an int: ", value)
    }
}
fmt.Println(a, b)

http://play.golang.org/p/Kbs3rbu2Rw

Func return value is interface{} but real return value is []interface{}, so try this instead:

func main() {
    values := returnValue.([]interface{})
    for i := range values {
        fmt.Println(values[i])
    }
}