Go - Multidimensional Array Example

In this example, we will show you how to use multi-dimensional array in Go with an example.

We can create multidimensional arrays in Go. We need additional pairs of square and curly brackets for additional array dimension.

Go - Multidimensional Array Example


package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {

    a := [2][2]int{

        {1, 2},
        {3, 4}, // the trailing comma is mandatory
    }

    fmt.Println(a)

    var b [2][2]int

    rand.Seed(time.Now().UnixNano())

    for i := 0; i < 2; i++ {
        for j := 0; j < 2; j++ {
            b[i][j] = rand.Intn(10)
        }
    }

    fmt.Println(b)
}

Output:

[[1 2] [3 4]]
[[0 8] [7 2]]