Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert interface{} to []int?

Tags:

go

I am programming in Go programming language.

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

I have tried

interface_variable.([]int)

The error I got is:

panic: interface conversion: interface is []interface {}, not []int
like image 414
user3534472 Avatar asked Jun 27 '14 13:06

user3534472


2 Answers

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

the 2022 answer

https://go.dev/play/p/yeihkfIZ90U

func ConvertSlice[E any](in []any) (out []E) {
    out = make([]E, 0, len(in))
    for _, v := range in {
        out = append(out, v.(E))
    }
    return
}

the pre-go1.18 answer

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)
}
like image 120
OneOfOne Avatar answered Nov 09 '22 00:11

OneOfOne


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

like image 37
rvignacio Avatar answered Nov 09 '22 02:11

rvignacio