Home »
Golang
Go Language - Multi-dimensional Arrays
Go multidimensional array is simply an array containing other arrays as its elements. The most common type of multidimensional array is the two-dimensional array, which is useful for representing matrices, tables, or grids.
Declaring Multidimensional Arrays
In Go, multidimensional arrays are declared using multiple sets of square brackets.
Syntax
The syntax for declaring a multidimensional array in Go is shown below:
package main
import "fmt"
func main() {
var arr [3][3]int // 3x3 multidimensional array
}
Declaring and Initializing Multidimensional Arrays
Multidimensional arrays can be initialized during declaration. Below is an example of a 2x2 multidimensional array:
Example
package main
import "fmt"
func main() {
// Declare and initialize a 2x2 array
var arr = [2][2]int{{1, 2}, {3, 4}}
fmt.Println(arr)
}
When executed, this program outputs:
[[1 2] [3 4]]
Accessing Elements
Elements in a multidimensional array can be accessed using their indices. Below is an example of accessing an element:
Example
package main
import "fmt"
func main() {
arr := [2][2]int{{5, 10}, {15, 20}}
fmt.Println("Element at [1][0]:", arr[1][0])
}
When executed, this program outputs:
Element at [1][0]: 15
Iterating Through a Multidimensional Array
You can use nested loops to iterate through each element of a multidimensional array. Below is an example of iterating through a 2x3 array:
Example
package main
import "fmt"
func main() {
arr := [2][3]int{{1, 2, 3}, {4, 5, 6}}
for i := 0; i < len(arr); i++ {
for j := 0; j < len(arr[i]); j++ {
fmt.Print(arr[i][j], " ")
}
fmt.Println()
}
}
When executed, this program outputs:
1 2 3
4 5 6
Using Range to Iterate
The range
keyword can be used to iterate over a multidimensional array in a more readable way. Below is an example of using range
:
Example
package main
import "fmt"
func main() {
arr := [2][2]int{{7, 8}, {9, 10}}
for _, row := range arr {
for _, val := range row {
fmt.Print(val, " ")
}
fmt.Println()
}
}
When executed, this program outputs:
7 8
9 10
Advertisement
Advertisement