gpt4 book ai didi

arrays - 如何使用for循环遍历2D数组

转载 作者:行者123 更新时间:2023-12-01 22:06:03 24 4
gpt4 key购买 nike

package main

import (
"fmt"
)

func main() {
grid := [][]int{
{0, 1, 2, 3},
{4, 5, 6, 7},
}
for _, array := range grid[0] {
for j := range array {
fmt.Print(array[j], " ")
}
fmt.Println()

}
}

这就是我现在拥有的内容,我试图遍历每一列,但是出现编译错误以下
./prog.go:13:12: cannot range over array (type int)

grid是[] [] int数组。我正在尝试将数组设置为每一列并遍历该列。

PlayGround

最佳答案

似乎您的内部range中缺少一个变量名。

https://tour.golang.org/moretypes/16:

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.



下面的代码已修复(可运行示例 https://play.golang.org/p/6uaM2IEm9lR)
package main

import (
"fmt"
)

func main() {
grid := [][]int{
{0, 1, 2, 3},
{4, 5, 6, 7},
}
for _, col := range grid {
for _, value := range col {
fmt.Println(value)
}
}
}

关于arrays - 如何使用for循环遍历2D数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61625571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com