英文:
about golang interface loop
问题
我想打印一个像下面这样复杂的数据集
package main
import (
"fmt"
// "reflect"
)
func main() {
var initData []interface{}
initData[0] = map[string]interface{}{
"name": "k1",
"type": "line",
"data": []int{1, 2, 3, 4},
}
initData[1] = map[string]interface{}{
"name": "k2",
"type": "circle",
"data": []int{11, 12, 13, 14},
}
for _, data := range initData {
for k, v := range data {
fmt.Println(k)
for _, sv := range v {
fmt.Println(" " + sv)
}
}
}
}
但是出现了错误
./maps-in-maps.go:56: cannot range over data (type interface {})
有什么帮助吗?尝试将接口类型的数据集转换为可迭代的数组或切片。
英文:
I wanto print a complicate dataset like bellowing
package main
import (
"fmt"
// "reflect"
)
func main() {
var initData []interface{}
initData[0] = map[string]interface{}{
"name": "k1",
"type": "line",
"data": []int{1, 2, 3, 4},
}
initData[1] = map[string]interface{}{
"name": "k2",
"type": "circle",
"data": []int{11, 12, 13, 14},
}
for _, data := range initData {
for k, v := range data {
fmt.Println(k)
for _, sv := range v {
fmt.Println(" " + sv)
}
}
}
}
but get an error
./maps-in-maps.go:56: cannot range over data (type interface {})
any help? to try to concert the interface typed dataset to interable like arry or slice
答案1
得分: 6
你必须首先对每个interface{}
级别进行类型断言,在这种情况下,在map[string]interface{}
级别使用类型断言,因为我们知道一个确定的类型,并使用类型开关来检查下一级中每个嵌套值的预期类型。
initData := []interface{}{
map[string]interface{}{
"name": "k1",
"type": "line",
"data": []int{1, 2, 3, 4},
},
map[string]interface{}{
"name": "k2",
"type": "circle",
"data": []int{11, 12, 13, 14},
},
}
for _, data := range initData {
for _, v := range data.(map[string]interface{}) {
switch t := v.(type) {
case string, []int:
fmt.Println(t)
default:
fmt.Println("wrong type")
}
}
}
在这里运行示例 链接。
英文:
You must type assert each interface{}
level first, in this case, use a type assertion at map[string]interface{}
level since we know a definite type, and a type switch to check anticipated types for each nested value in the next level.
initData := []interface{}{
map[string]interface{}{
"name": "k1",
"type": "line",
"data": []int{1, 2, 3, 4},
},
map[string]interface{}{
"name": "k2",
"type": "circle",
"data": []int{11, 12, 13, 14},
},
}
for _, data := range initData {
for _, v := range data.(map[string]interface{}) {
switch t := v.(type) {
case string, []int:
fmt.Println(t)
default:
fmt.Println("wrong type")
}
}
}
}
Run playground here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论