Lesson 2

Understanding Multidimensional Arrays in Go

Topic Overview and Introduction

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!

Understanding Multidimensional Arrays

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:

1var chocolates [3][3]string

"chocolates" here is a 2D array that can hold 9 strings in a 3x3 distribution.

Creating and Initializing Multidimensional Arrays

To fill our box of chocolates, we initialize our array:

1var 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.

Accessing Values in Multidimensional Arrays

To access elements in a 2D array, two indices are used: the first is for the row and the second is for the column.

1selectedChoc := chocolates[0][2] 2fmt.Println("Selected chocolate: ", selectedChoc) // white
Lesson Summary

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!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.