Arrays, Slices, and Maps
Go provides flexible composite types for grouping data.Arrays
An array is a fixed-size sequence of elements of a specific type.Slices
Slices are dynamically-sized, flexible views into the elements of an array. In practice, slices are much more common than arrays.Slice Internals
A slice does not store any data itself. It just describes a section of an underlying array. Understanding this is crucial for writing efficient Go code.- Pointer: Points to the first element of the slice in the underlying array.
- Length: The number of elements currently in the slice (accessible via
len()). - Capacity: The total number of elements in the underlying array from the slice’s starting point (accessible via
cap()).
Creating Slices
You can create slices usingmake, which allocates a new underlying array:
Appending to Slices
The built-inappend function adds elements to a slice. Here’s what happens under the hood:
- If
len < cap: The element is added to the existing array, and length is incremented. - If
len == cap: A new, larger array is allocated (typically 2x the current capacity), existing elements are copied, and the new element is added.
append returns a new slice value. You must assign it back:
Range
Therange form of the for loop iterates over a slice or map.
_.
Maps
A map maps keys to values. The zero value of a map isnil.