登录
首页 >  Golang >  Go问答

在 Golang 中,嵌套循环无法正确遍历包含数组元素的结构

来源:stackoverflow

时间:2024-03-20 19:06:24 175浏览 收藏

在 Go 中嵌套循环遍历包含数组元素的结构时,重新定义循环变量会导致索引操作错误。错误提示“无效操作:checkItems[i](类型 struct {...} 不支持索引)”表明循环变量不再指向原始列表,而是指向单个结构体元素。

问题内容

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

./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


正确答案


在这一行for i, checkitems := range checkitems中,你重新定义了checkitems,它覆盖了原来的checkitems,所以现在checkitems只表示原来的checkitems中的一项,其类型应该是zqbczq bstruct,不再是列表了。

解决方案是将第二个 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])
        }

    }
}

今天关于《在 Golang 中,嵌套循环无法正确遍历包含数组元素的结构》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>