Use multidimensional arrays
Use multidimensional arrays
A multidimensional array contains arrays as its elements. [2][3]int contains two rows, each with three integers. Use grid[row][column] to select a cell. Both dimensions are fixed.
package main
import "fmt"
func main() { grid := [2][3]int{{1, 2, 3}, {4, 5, 6}} fmt.Println(grid[1][2]) grid[0][1] = 9 fmt.Println(grid) fmt.Println(len(grid), len(grid[0]))}The first index selects the row and the second the column. Inner literals may omit their repeated type. len(grid) counts rows, not all cells. Each index must be within its own dimension.
Expected output:
6[[1 9 3] [4 5 6]]2 3Traverse rows and columns
package main
import "fmt"
func main() { grid := [2][3]int{{1, 2, 3}, {4, 5, 6}} for _, row := range grid { sum := 0 for _, v := range row { sum += v } fmt.Println(sum) } for r := range grid { for c := range grid[r] { grid[r][c]++ } } fmt.Println(grid)}The row variable holds a copied array, suitable for reading. To modify original cells, use both indexes. For tables with variable row lengths, consider slices in the next chapter.
Expected output:
615[[2 3 4] [5 6 7]]Try it locally
Create a 2-by-2 array with rows {2,3} and {4,5}. Sum all cells with nested range loops; print total and row 1, column 0.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 05: Use multidimensional arrays
Check the lesson objective before moving on.
How many integers are in [2][3]int?
Which updates row 1, column 0?