Appendix C. Arrays, Slices, and Maps
Go has three built-in collection types: arrays, slices, and maps.
- Arrays are fixed-length collections of elements of the same type.
- Slices are like dynamic arrays that can expand and shrink.
- Maps are key-value pairs that allow constant-time access to values via their keys.
NOTE
Access time may be degraded if a map has many hash collisions. Learn more about map internals at https://www.youtube.com/watch?v=Tl7mi9QmLns.
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.
Say we want to represent RGB (red, green, and blue) colors as integers in an array:
rgb := [3]byte{41, 190, 176} #A
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 three bytes. So, we cannot store more than three bytes in this array unless we change its type to a larger number, such as [42]byte, and recompile the program.
TIP
An array's length and element type together determine its type.
Let's now discuss array operations and the pass-by-value mechanics of arrays.
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.
