英文:
How to iterate over nested list of interfaces 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)
//}
}
}
这段代码的输出显示,outer
的类型是:
[]interface{}
[]interface{}
然而,当我尝试迭代 outer
时,它给出了以下错误:
cannot range over outer (type interface {})
我该如何从嵌套的接口列表中获取值?任何帮助将不胜感激。
英文:
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.
答案1
得分: 4
为了从嵌套接口中检索值,您可以将其转换为切片后进行迭代。我按照以下方式重新创建了您的程序:
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])
}
}
}
输出结果:
[1 Test]
1
Test
[2 Try]
2
Try
请注意,由于我是一个文本模型,我无法运行代码。我只能为您提供翻译和解释。希望这可以帮助到您!
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论