Slices
Explore the concept of slices in Go as dynamic references to segments of arrays. Understand slice memory structure, length, capacity, and how slices share data with underlying arrays. Learn to initialize, manipulate, and expand slices effectively for efficient Go programming.
We'll cover the following...
Concept
A slice is a reference to a contiguous segment (section) of an array (which we will call the underlying array, and which is usually anonymous), so a slice is a reference type (more like the array type in C/C++, or the list type in Python). This section can be the entire array or a subset of the items indicated by a start and an end index (the item at the end index is not included in the slice). Slices provide a dynamic window to the underlying array.
A slice in memory is a structure with 3 fields:
- a pointer to the underlying array
- the length of the slice
- the capacity of the slice
Slices are indexable and have a length given by the len() function.
The slice-index of a given item can be less than the index of the same element in the underlying array. Unlike an array, the length of a slice can change during the execution of the code, minimally 0 and maximally the length of the underlying array, which means a slice is a variable-length array.
The built-in capacity function cap() of a slice is a measure of how long a slice can become. It is the length of the slice + the length of the array beyond the slice. If s is a slice, cap is the size of the array from s[0] to the end of the
array. A slice’s length can never exceed its capacity, so the following statement is always true for a slice s:
0 <= len(s) <= cap(s)
This is illustrated in the following figure, where the ...