How to convert interface {} to [] int?

I program in the Go programming language.

Say there a type variable interface{}that contains an array of integers. How to convert interface{}back to []int?

I tried

interface_variable.([]int)

I got an error:

panic: interface conversion: interface is []interface {}, not []int
+4
source share
3 answers

This is []interface{}not only one interface{}, you need to skip it and convert:

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)
}
+9
source

As others have said, you must iterate over a slice and transform objects one at a time. It is better to use a type switch within the range to avoid panic:

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

+2
source

Func - {}, [] {}, :

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

Source: https://habr.com/ru/post/1546310/


All Articles