Hello and welcome! Today, we're diving into multidimensional arrays in Go, which are arrays of arrays. Their organizational structure is similar to a checkerboard, where each square can hold a value. By the end of our journey, you'll know how to create, initialize, and work with these arrays. Let's get started!
A two-dimensional (2D) array in Go is much like a grid, consisting of multiple rows (the array) and columns (the arrays within the array).
Imagine a box of chocolates with several rows and columns - the box is the array, and each cell is an array element. In Go, a similar 2D array takes the form:
Go1var chocolates [3][3]string
"chocolates"
here is a 2D array that can hold 9 strings in a 3x3 distribution.
To fill our box of chocolates, we initialize our array:
Go1var chocolates = [3][3]string { 2 {"dark", "white", "milk"}, 3 {"hazelnut", "almond", "peanut"}, 4 {"caramel", "mint", "coffee"}}
Each row (an array) holds several columns (array elements). Since Go arrays are of a fixed size, we define this size at the time of creation and cannot change it thereafter.
To access elements in a 2D array, two indices are used: the first is for the row and the second is for the column.
Go1selectedChoc := chocolates[0][2] 2fmt.Println("Selected chocolate: ", selectedChoc) // white
Marvelous! We now have a solid understanding of multidimensional arrays in Go. With the initialization, creation, and extraction of values under your belt, you're ready for practice exercises. Stay tuned for these innovative exercises that provide applied techniques for writing more effective and efficient code in Go!