0

I have the below code written in Golang:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var i []interface{}
    var j []interface{}
    var k []interface{}
    
    i = append(i, 1)
    i = append(i, "Test")
    
    j = append(j, 2)
    j = append(j, "Try")
    
    k = append(k, i)
    k = append(k, j)
    
    
    for _, outer := range k {
        fmt.Println(reflect.TypeOf(outer))
        //for _, inner := range outer {
        //  fmt.Println(inner)
        //}
    }
}

The output of this code shows that outer is a type of:

[]interface{}
[]interface{}

However, when I try to iterate over outer it gives me the error:

cannot range over outer (type interface {})

How can I retrieve the values from the nested list of interfaces? Any help would be appreciated.

codecrazy46
  • 275
  • 1
  • 5
  • 14
  • 2
    Use type assertion: `outer.([]interface{})` to obtain a slice from the `interface{}` value, you can iterate over that. – icza Jun 25 '21 at 07:59
  • Thanks @icza for the help. I am able to iterate over the list of interfaces now. – codecrazy46 Jun 25 '21 at 08:29
  • 1
    Sidenote: if you know that `k` will contain slices you should think about changing it to type `[][]interface{}`, then you don't need the type assertion. – lmazgon Jun 25 '21 at 11:37

1 Answers1

4

In order to retrieve the values from nested interfaces you can iterate over it after converting it to a slice. I recreated your program as follows:

package main

import (
    "fmt"
)

func main() {
    var i []interface{}
    var j []interface{}
    var k []interface{}

    i = append(i, 1)
    i = append(i, "Test")

    j = append(j, 2)
    j = append(j, "Try")

    k = append(k, i)
    k = append(k, j)

    for _, outer := range k {

        fmt.Println(outer.([]interface{}))
        for z := 0; z < len(outer.([]interface{})); z++ {
            fmt.Println(outer.([]interface{})[z])
        }

    }
}

Output:

[1 Test]
1
Test
[2 Try]
2
Try
Gopher
  • 721
  • 3
  • 8