-1

I wrote this example code (https://play.golang.org/p/u_oz5X4aU07):

func main() {
    var obj interface{}
    json.Unmarshal([]byte("[[1,2],[3,4]]"), &obj)
    val := obj.([][]int)
    fmt.Println(val)
}

Why I get the error:

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

Is there a simple way to transform obj in a slice of slice?

This code works, but I'd like something more compact and efficient.

    var val [][]float64
    for r, v := range obj.([]interface{}) {
        val = append(val,nil)
        for _, w := range v.([]interface{}) {
            val[r] = append(val[r], w.(float64))
        }
    }
Agostino
  • 13
  • 3

1 Answers1

0

No, ultimately you'll have to loop over the two slices!

You can read here why you can't just use one as the other:

https://research.swtch.com/interfaces

This answer might also be useful:

Why golang struct array cannot be assigned to an interface array

Essentially it's because the interface is stored as a 2 word pair, one defining the type and one the values.

You have to manually convert to the required type by visiting all the values in for-range loops.

Zak
  • 5,515
  • 21
  • 33