我试图以这种方式使用范围功能来印刷电路板,但它确实起作用了,但是我无法解决原因?行,列的计数如何累加?
package main
import "fmt"
func main() {
var board [2][2][2]string
for row := range board {
for column := range board {
for third := range board {
fmt.Print(row, column, third)
fmt.Println()
}
}
}
}
答案 0 :(得分:4)
您的代码没有执行您认为的操作。您要遍历每个循环中的顶级数组。每个数组只有2个元素,这给您带来了成功的幻觉。如果您打印出值而不是索引(playground),则失败更明显:
var board = [2][2][2]string{
{
{"a", "b"},
{"c", "d"},
},
{
{"e", "f"},
{"g", "h"},
},
}
for _, rowValue := range board {
for _, columnValue := range board {
for _, thirdValue := range board {
fmt.Println(rowValue, columnValue, thirdValue)
fmt.Println()
}
}
}
您想要的是让每个内部循环迭代内部数组(playground link):
for _, rowValue := range board {
for _, columnValue := range rowValue {
for _, thirdValue := range columnValue {
fmt.Printf("\t%s", thirdValue)
}
fmt.Printf("\n")
}
fmt.Printf("\n\n")
}
给出以下输出:
a b
c d
e f
g h