How to convert interface{} to []int?

Issue

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

Solution

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

Answered By – OneOfOne

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.