douwen1929
2018-06-19 10:01
浏览 40
已采纳

切片中的接口转换

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))
        }
    }
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwu4834 2018-06-19 12:41
    已采纳

    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.

    打赏 评论

相关推荐 更多相似问题