Junior
How does the append function work for slices in Go?
sobes.tech AI
Answer from AI
The append function adds elements to a slice. It returns a new slice because the original may be modified.
When adding elements, append can use the existing capacity of the slice if it is sufficient. In this case, the new slice will point to the same underlying array as the original, but its length will increase.
If the capacity is insufficient, append allocates a new, larger underlying array, copies the elements from the original slice into it, and adds the new elements. The new slice will point to this new array.
Typically, the size of the new array doubles when capacity is insufficient to minimize the number of future reallocations.
// Example of using append
slice1 := []int{1, 2, 3}
fmt.Printf("Slice1: %v, Len: %d, Cap: %d\n", slice1, len(slice1), cap(slice1)) // Output: Slice1: [1 2 3], Len: 3, Cap: 3
// Adding one element - capacity is enough
slice2 := append(slice1, 4)
fmt.Printf("Slice2: %v, Len: %d, Cap: %d\n", slice2, len(slice2), cap(slice2)) // Output: Slice2: [1 2 3 4], Len: 4, Cap: 6 (capacity doubled)
// Adding multiple elements
slice3 := append(slice2, 5, 6, 7)
fmt.Printf("Slice3: %v, Len: %d, Cap: %d\n", slice3, len(slice3), cap(slice3)) // Output: Slice3: [1 2 3 4 5 6 7], Len: 7, Cap: 12 (capacity doubled again)
// Adding elements from another slice using ...
slice4 := []int{8, 9}
slice5 := append(slice3, slice4...)
fmt.Printf("Slice5: %v, Len: %d, Cap: %d\n", slice5, len(slice5), cap(slice5)) // Output: Slice5: [1 2 3 4 5 6 7 8 9], Len: 9, Cap: 12