I wrote the code:
switch v.(type) {
case []interface{}:
fmt.Println(reflect.TypeOf(v))
for index, element := range v {
fmt.Println("Inside for")
}
default:
fmt.Println("I don't know how to handle this.")
}
Now, my reflect.TypeOf(v)
outputs the type as []interface {}
. But, I'm not able to iterate over the array of interfaces. I encounter the error:cannot range over v (type interface {})
. Could someone please explain me why ? Also, what's the workaround ?
In a type switch, if you wish to access the variable casted to the appropriate type just use something like switch x := v.(type)
and in each case of the switch x
will be of the appropriate value. The spec has an example of this. You can even do switch v := v.(type)
and within the switch statement there will be a shadowed version of v.
E.g.:
switch x := v.(type) {
case []interface{}:
fmt.Printf("got %T
", x)
for i, e := range x {
fmt.Println(i, e)
}
default:
fmt.Printf("I don't know how to handle %T
", v)
}
Also note that you can just use "%T" with fmt.Printf
instead of (directly) using the reflect package when you just want to print the type of a variable.
You can always use v.([]interface{})
. I ran into the same problem when trying to parse hetrogeneous json objects that had to be treated as interfaces.
Although that might not work in your loop unless you know something about your data beforehand.