嵌套的for循环用于遍历包含数组元素的结构体在golang中无法正常工作。

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

Nested for loop to iterate through struct containing array elements is not working in golang

问题

尝试遍历项目列表时出现以下错误:

./prog.go:25:39: invalid operation: checkItems[i] (type struct { items string; size []string; color []string } does not support indexing)
./prog.go:28:69: invalid operation: checkItems[i] (type struct { items string; size []string; color []string } does not support indexing)

以下是代码:
https://play.golang.org/p/zdCe-BC2t_D

英文:

Trying to iterate through item list but getting below error :

./prog.go:25:39: invalid operation: checkItems[i] (type struct { items string; size []string; color []string } does not support indexing)
./prog.go:28:69: invalid operation: checkItems[i] (type struct { items string; size []string; color []string } does not support indexing)

Here is the code :
https://play.golang.org/p/zdCe-BC2t_D

答案1

得分: 1

在这行代码for i, checkItems := range checkItems中,你重新定义了checkItems,覆盖了原来的checkItems,所以现在checkItems只表示原来的checkItems中的一个项目,其类型应该是struct,而不再是列表。

解决方法是将第二个checkItems重命名为另一个名称,比如checkItem

package main

import (
	"fmt"
)

func main() {
	checkItems := []struct {
		items string
		size  []string
		color []string
	}{
		{
			items: "Shirt",
			size:  []string{"XL", "L", "S", "XS"},
			color: []string{"Brown", "Black", "White"},
		},
		{
			items: "Shoes",
			size:  []string{"10", "8"},
			color: []string{"White", "Brown"},
		},
	}
	for i, checkItem := range checkItems {
		for j, _ := range checkItem.size {

			fmt.Println("Hello, playground", i, "checkitems", checkItem)
			fmt.Println("Hello, playground", j, "checkitems size", checkItems[i].size[j])
		}

	}
}
英文:

In this line for i, checkItems := range checkItems, you redefine checkItems which overwrite the original checkItems, so now checkItems only indicates one item of original checkItems whose type should be struct, not the list any more.

The solution is rename the second checkItems into another one like checkItem

package main

import (
	"fmt"
)

func main() {
	checkItems := []struct {
		items string
		size  []string
		color []string
	}{
		{
			items: "Shirt",
			size:  []string{"XL", "L", "S", "XS"},
			color: []string{"Brown", "Black", "White"},
		},
		{
			items: "Shoes",
			size:  []string{"10", "8"},
			color: []string{"White", "Brown"},
		},
	}
	for i, checkItem := range checkItems {
		for j, _ := range checkItem.size {

			fmt.Println("Hello, playground", i, "checkitems", checkItem)
			fmt.Println("Hello, playground", j, "checkitems size", checkItems[i].size[j])
		}

	}
}

huangapple
  • 本文由 发表于 2021年5月21日 13:46:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/67631417.html
匿名

发表评论

匿名网友

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

确定