英文:
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])
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论