The slice, len, and cap
A slice is a header over an array. append sometimes writes into that same array, and sometimes allocates a new one.
A slice is a structure of three words: a pointer to an array, the length len, and the capacity cap. The literal []int{1, 2, 3} creates an array and a slice that sees all of it. The slice expression a[:2] is another header on the same array, with its own length.
append adds elements. If there is room in the tail of the array (len < cap), the write goes into the same array. This is a contract, not "usually so":
a := []int{1, 2, 3}
b := a[:2]
b = append(b, 9)
// a тоже стал [1 2 9]: у b хватало cap
If there is no room, append allocates a new array, copies the elements, and returns a new header. The old slice does not change. The language does not promise how much cap will grow. You cannot write code that depends on "it always doubles". You can rely only on the new length being enough.
A nil slice behaves calmly: len is 0, range does nothing, and append returns a slice that is no longer nil. You cannot compare slices with ==, except comparison with nil. For the contents there is slices.Equal.
When you pass a slice to a function, you copy the header, not the elements. The function can change elements of the shared array. It cannot replace the caller's header unless you return a new slice. That is why append is always used as s = append(s, x). A forgotten s = is a classic bug: the elements may have moved to a new array, while the caller still holds the old header.
The slices package covers everyday operations: Contains, Clone, Sort, Delete, Index. You write your own loop when it holds domain logic, not a search for an element.
Practice
A shared array
What ends up in
a? Write the numbers separated by spaces.a := []int{1, 2, 3} b := a[:2] b = append(b, 9)Only the positives
Write
Positive(nums []int) []int. Return a new slice of only the numbers greater than zero, in the original order. Skip zero and the negatives. For an empty input return an empty slice. Nil is not required: either one will do. The check looks at text of the form[4 2]or[].Where append goes
Why is the result of
appendalmost always assigned back into the variable?- Otherwise append will not compile
- Otherwise you can lose elements if a new array was allocated
- The assignment is needed only for maps, not for slices
- To grow cap by exactly two, which the specification guarantees