- 使用嵌套循环遍历二维数组或切片,如下所示:
arr := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr[i]); j++ {
fmt.Println(arr[i][j])
}
}
- 使用range关键字遍历二维数组或切片,如下所示:
arr := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for _, row := range arr {
for _, val := range row {
fmt.Println(val)
}
}
- 使用索引和值同时遍历二维数组或切片,如下所示:
arr := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i, row := range arr {
for j, val := range row {
fmt.Printf("arr[%d][%d] = %d\n", i, j, val)
}
}