Use the built-in append() function to add elements to a slice, which automatically handles capacity expansion and returns a new slice header. You can append single values, multiple values, or entire slices by passing them as arguments to this function.
Here is a practical example showing how to append a single element and multiple elements at once:
package main
import "fmt"
func main() {
// Initialize a slice with capacity 3
nums := []int{1, 2, 3}
// Append a single value
nums = append(nums, 4)
// Append multiple values
nums = append(nums, 5, 6)
fmt.Println("Result:", nums) // Output: Result: [1 2 3 4 5 6]
}
When appending another slice, use the ... operator to unpack its elements. This is efficient and avoids creating intermediate copies if the destination slice has enough capacity:
package main
import "fmt"
func main() {
sliceA := []int{1, 2}
sliceB := []int{3, 4, 5}
// Append all elements from sliceB to sliceA
combined := append(sliceA, sliceB...)
fmt.Println("Combined:", combined) // Output: Combined: [1 2 3 4 5]
}
Remember that append returns a new slice header; you must assign the result back to a variable. If the underlying array has sufficient capacity, append reuses it, but if not, it allocates a new, larger array and copies the data. This makes append safe to use without manually checking len vs cap, though pre-allocating with make can improve performance in tight loops if you know the final size.
// Pre-allocating for performance in a loop
results := make([]string, 0, 100) // Capacity 100, length 0
for i := 0; i < 100; i++ {
results = append(results, fmt.Sprintf("item %d", i))
}
Avoid appending to a nil slice without initialization if you need a specific capacity, as make is required to set that capacity upfront. Otherwise, append works seamlessly on nil slices, treating them as empty slices with zero length and capacity.