Two-Dimensional Slices
Some data has rows and columns, like a game board or a table of numbers. In Go you can store it as a slice of slices, a slice whose elements are slices themselves. Its type is [][]int, with one pair of brackets for the rows and one for the columns.
package main
import "fmt"
func main() {
grid := [][]int{
{1, 2, 3},
{4, 5, 6},
}
fmt.Println(grid)
fmt.Println(grid[1])
fmt.Println(grid[1][2])
}
Output:
[[1 2 3] [4 5 6]]
[4 5 6]
6
Each inner {...} is one row. grid[1] is the second row, and it is a normal []int slice. grid[1][2] takes that row and then its element at index 2. So the first index picks the row, and the second index picks the column:
col 0 col 1 col 2
row 0: 1 2 3
row 1: 4 5 6
len(grid) is the number of rows. len(grid[0]) is the number of elements in the first row, which is the number of columns.
Nested loops
To visit every element, put one loop inside another, as in the Nested Loops lesson. The outer loop goes over the rows, and the inner loop goes over the elements of one row:
grid := [][]int{
{1, 2, 3},
{4, 5, 6},
}
total := 0
for _, row := range grid {
for _, value := range row {
total += value
}
}
fmt.Println("Total:", total)
Output:
Total: 21
On each pass of the outer loop, row is one whole row. The inner loop then adds that row's values.
Building a grid with make
When the size comes from input, use make. But make([][]int, 3) only makes the outer slice. Each of its 3 rows is an empty nil slice, with no elements yet. Writing into a row then fails:
grid := make([][]int, 3)
fmt.Println(grid)
grid[1][2] = 7
Output:
[[] [] []]
panic: runtime error: index out of range [2] with length 0
You must make every row too, usually in a loop right after the outer make:
rows, cols := 3, 4
grid := make([][]int, rows)
for r := range grid {
grid[r] = make([]int, cols)
}
grid[1][2] = 7
fmt.Println(grid)
Output:
[[0 0 0 0] [0 0 7 0] [0 0 0 0]]
With the indexes r and c, nested loops can also fill a grid. This one builds a small multiplication table and prints it one row per line:
table := make([][]int, 3)
for r := range table {
table[r] = make([]int, 3)
for c := range table[r] {
table[r][c] = (r + 1) * (c + 1)
}
}
for _, row := range table {
fmt.Println(row)
}
Output:
[1 2 3]
[2 4 6]
[3 6 9]
Because each row is its own slice, rows can also have different lengths. For a grid, keep them all the same length.
Fixed grids with arrays
When the size never changes, like a 3 by 3 board for tic-tac-toe, you can use an array of arrays instead. [3][3]int is 3 rows of 3 int values. Like every array, it starts filled with zero values, so it needs no make:
var board [3][3]int
board[1][1] = 5
fmt.Println(board)
Output:
[[0 0 0] [0 5 0] [0 0 0]]
In the exercise, read a grid of numbers into a slice of slices and print the sum of each row.