Skip to content

How to make a 2D or 3D array in Go

Technically what we’re making here is a slice with a defined length. It’s not possible to make an array in Go with a non constant number.

Initializing a multidimensional array in Go is tricky, you can create a simple fixed size array with one line of code but if you need a multidimensional array you need to define each element separately.

2D Array with a size of NxM

package main

import (
	"fmt"
)

func main() {
	var N, M = 3, 4
	array := make([][]int, N)
	for n := 0; n < N; n++ {
		array[n] = make([]int, M)
	}

	fmt.Printf("%#v", array)

	// Output:
	// [][]int{[]int{0, 0, 0, 0}, []int{0, 0, 0, 0}, []int{0, 0, 0, 0}}
}

3D Array with a size of NxMxK

package main

import (
	"fmt"
)

func main() {
	var N, M, K = 2, 3, 4
	array := make([][][]int, N)
	for n := 0; n < N; n++ {
		array[n] = make([][]int, M)
		for m := 0; m < M; m++ {
			array[n][m] = make([]int, K)
		}
	}
	fmt.Printf("%#v", array)

	// Output: 
	// [][][]int{[][]int{[]int{0, 0, 0, 0}, []int{0, 0, 0, 0}, []int{0, 0, 0, 0}}, [][]int{[]int{0, 0, 0, 0}, []int{0, 0, 0, 0}, []int{0, 0, 0, 0}}}
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *