How to convert interface{} to []int?


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


The error I got is:

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


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

the 2022 answer

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

the pre-go1.18 answer

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.