W3Basic Logo

Go Multidimensional Array


In order to represent a chess board, a matrix or an image, a simple array is not the best choice. Indeed, if you wanted to store the state of the 64 squares of a chess board by using an array of type [64]int, you would have to use a formula to convert the coordinates of a square into an index in the array, and vice versa.

func index(x, y int) int {
	return y*8 + x
}

func square(i int) (x, y int) {
	return i % 8, i / 8
}

This is doable but not very convenient. A better solution is to use a multidimensional array, which is an array of arrays. For example, the following code declares a two-dimensional array of type [][]int:

var board [8][8]int

And indexing it is as simple as:

board[0][0] = 1

Under the hood, a multidimensional array is a one-dimensional array of one-dimensional arrays. As a consequence, board[0] is a one-dimensional array of type [8]int, and board[0][0] is an integer.

Creating and Accessing Multidimensional Array in Go

Let us take a simple example to create and print the multidimensional array in Go.

package main

import "fmt"

func main() {
	// 2 x 2 Multidimensional Array
	x := [2][2]int{{1, 2}, {3, 4}}

	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			fmt.Println(x[i][j])
		}
	}
}

Output

1
2
3
4

Images are three-dimensional arrays

You can think of an image as a tridimensional object, three layers (respectively red, green and blue) of two-dimensional arrays. The type of a 64*64 color image would thus be [64][64][3]uint8.

Note: The uint8 type is an alias for the byte type, which is a byte (8 bits) unsigned integer, so the values of the pixels are in the range [0, 255]. It would be a waste of memory to use a 32-bit integer for each pixel, since the values are so small.

Finding the maximum value in a two-dimensional array

To better understand multidimensional arrays, let's write a function that finds the maximum value in a two-dimensional array of integers. The main logic is the same as in the case of a simple (one-dimensional) array, but we need to use two nested for loops:

func max2D(arr [][]int) int {
	max := arr[0][0]
	for i, row := range arr {
		for j, val := range row {
			if val > max {
				max = val
			}
		}
	}
	return max
}

© 2023 W3Basic. All rights reserved.

Follow Us: