appendix CArrays, slices, and maps

 

Go has three built-in collection types:

  • Arrays are fixed-length collections of elements of the same type.
  • Slices are dynamic arrays that can expand and shrink.
  • Maps are key–value pairs that allow constant-time access to values via their keys.

C.1 Arrays

Arrays are helpful when we have a fixed number of items. We can declare arrays of any length and type, such as [10]string, [16]bool, etc. Suppose that we want to represent red, green, and blue (RGB) colors as integers. We can declare the following array:

rgb := [3]byte{41, 190, 176}

This rgb variable stores an array with three byte elements:

  • [3] is the array’s length.
  • byte is the array’s element type.

An array’s length and element type together determine its type. The rgb array’s type is [3]byte, an array of 3 bytes. We cannot store more than 3 bytes in this array unless we change its type to a larger number, such as [42]byte, and recompile the program.

C.1.1 Array operations

Figure C.1 illustrates the rgb array and the operations we can use on it.

Figure C.1 A byte array with three consecutive byte elements laid out in memory

We can get the rgb array’s length using the built-in len function:

len(rgb) #1

Zero-based indexing returns an array element at that index. This expression

rgb[0]

returns 41, and this one returns 176:

rgb[len(rgb)-1]

We can also loop over arrays (i is the index, and v is the next element’s copy):

Output: