使用范围的SIMPLE For循环如何以及为什么在Go中打印简单的3D数组?

时间:2019-03-20 11:50:11

标签: arrays go multidimensional-array

我试图以这种方式使用范围功能来印刷电路板,但它确实起作用了,但是我无法解决原因?行,列的计数如何累加?

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()
            }
        }
    }
}

1 个答案:

答案 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