如何在Golang中迭代嵌套的接口列表?

huangapple go评论84阅读模式
英文:

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 (
	&quot;fmt&quot;
)

func main() {
	var i []interface{}
	var j []interface{}
	var k []interface{}

	i = append(i, 1)
	i = append(i, &quot;Test&quot;)

	j = append(j, 2)
	j = append(j, &quot;Try&quot;)

	k = append(k, i)
	k = append(k, j)

	for _, outer := range k {

		fmt.Println(outer.([]interface{}))
		for z := 0; z &lt; len(outer.([]interface{})); z++ {
			fmt.Println(outer.([]interface{})[z])
		}

	}
}

Output:

[1 Test]
1
Test
[2 Try]
2
Try

huangapple
  • 本文由 发表于 2021年6月25日 15:57:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/68127492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定