Multidimensional Arrays in Go
Introduction
In Go, multidimensional arrays are arrays of arrays. They can be used to store data in a tabular form, such as matrices or tables. This tutorial will guide you through the basics of multidimensional arrays, including declaration, initialization, and accessing elements with examples in Go programming language.
Declaration
To declare a multidimensional array in Go, you need to specify the size of each dimension. For example, a 2-dimensional array with 3 rows and 4 columns can be declared as follows:
var array [3][4]int
This declares a 2D array of integers with 3 rows and 4 columns.
Initialization
You can initialize a multidimensional array at the time of declaration. Here’s an example:
var array = [3][4]int{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, }
This initializes the array with the given values. Each inner array represents a row in the 2D array.
Accessing Elements
You can access elements in a multidimensional array using the row and column indices. For example, to access the element in the second row and third column, you would do the following:
element := array[1][2]
Remember that array indices in Go are zero-based. So, the first row is index 0, the second row is index 1, and so on.
Example Program
Let’s look at a complete example program that declares, initializes, and accesses elements of a 2D array:
package main import "fmt" func main() { var array = [3][4]int{ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, } // Accessing elements fmt.Println("Element at [1][2]:", array[1][2]) // Iterating over elements fmt.Println("All elements in the array:") for i := 0; i < 3; i++ { for j := 0; j < 4; j++ { fmt.Print(array[i][j], " ") } fmt.Println() } }
Output:
Element at [1][2]: 7 All elements in the array: 1 2 3 4 5 6 7 8 9 10 11 12
This program declares and initializes a 2D array, accesses an element, and then iterates over all elements to print them.
Conclusion
In this tutorial, we covered the basics of multidimensional arrays in Go, including how to declare, initialize, and access elements. Multidimensional arrays are a powerful feature that can be used to manage complex data structures in a tabular format. With practice, you'll be able to use them effectively in your Go programs.