append
append adds elements to a slice and returns a slice that may use the same array or a newly allocated one. Always assign the result: s = append(s, v).
Detailed Explanation
append(s, 1, 2) is the only built-in way to grow a slice. If cap(s) - len(s) is large enough, it writes into the unused tail and returns a header with a larger len and the same pointer. If not, it allocates a bigger array, copies the old elements, writes the new ones, and returns a header that points at the new array. The original header in the caller is stale unless you assign.
Variadic extra arguments. append(s, a, b) or append(s, more...) when more is a []T. The types must match. To append a string's bytes to a []byte, append(buf, str...) is allowed as a special case.
Nil is a valid first argument. append(nil, 1) allocates and returns a one-element slice. This is why you can build a slice in a loop from a zero var s []T.
Aliasing is the hard part. t := s[1:2]; s = append(s, 9) may write 9 into the same array t sees, or it may allocate and leave t on the old array. After an append that might grow, assume other headers into the same array are independent only if you clipped capacity or copied.
append does not update other variables. func add(s []int, v int) { s = append(s, v) } is a no-op for the caller. Return the slice. The same rule applies to delete-by-append: s = append(s[:i], s[i+1:]...).
What it costs. Each growth copies the slice. Amortized cost per element is constant if you keep the returned header. Pre-sizing with make([]T, 0, n) removes the copies when n is known. Appending one byte at a time to a []byte without a cap is the classic accidental quadratic loop; strings.Builder or a sized make is the fix for text.
Code Examples
package main
import "fmt"
func main() {
var s []int
s = append(s, 1)
s = append(s, 2, 3)
more := []int{4, 5}
s = append(s, more...)
fmt.Println(s)
}func concat(a, b []byte) []byte {
return append(a, b...)
}
func appendString(buf []byte, s string) []byte {
return append(buf, s...) // special case for []byte
}func remove(s []int, i int) []int {
return append(s[:i], s[i+1:]...)
}Common Gotchas
Not assigning the result loses a reallocation
later reads use the old length and stale pointer.
`append` into a shared array overwrites siblings
clip capacity or `copy` before you treat two slices as independent.
First argument must be a slice
`append(array, v)` does not compile. Slice the array first.