- 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
len(rgb) #1
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: