Append to slice
suggest changeThe built-in function append(slice, elements...) adds one or more elements to a slice and returns the resulting slice.
Append a single value
a := []string{"hello"}
a = append(a, "world")
fmt.Printf("a: %#v\n", a)
a: []string{"hello", "world"}
Append multiple values
a := []string{"hello"}
a = append(a, "world", "now")
fmt.Printf("a: %#v\n", a)
a: []string{"hello", "world", "now"}
Append a slice to a slice
a := []string{"!"}
a2 := []string{"Hello", "world"}
a = append(a, a2...)
fmt.Printf("a: %#v\n", a)
a: []string{"!", "Hello", "world"}
Append might create a new slice
Maybe you noticed the pattern a = append(a, ....).
A slice stores its elements in a fixed-size array. When the number of elements would exceed that array, append allocates a new array and returns a slice that uses it. For efficiency, the new array has spare capacity, so the backing array is not reallocated on every append.
This program shows how many appends it takes before the backing array is reallocated.
var a []int
ptr := fmt.Sprintf("%p", a)
n := 0
nAppends := 0
for {
a = append(a, 1)
nAppends++
currPtr := fmt.Sprintf("%p", a)
if currPtr != ptr {
fmt.Printf("Appends needed to re-allocate slice: %d\n", nAppends)
nAppends = 0
ptr = currPtr
n++
if n == 6 {
break
}
}
}
Appends needed to re-allocate slice: 1
Appends needed to re-allocate slice: 1
Appends needed to re-allocate slice: 1
Appends needed to re-allocate slice: 2
Appends needed to re-allocate slice: 4
Appends needed to re-allocate slice: 8
As you can see, the number of appends between reallocations increases with the size of the slice.
Go doesn't allow comparing slices with == (except to nil). In the current implementation, the %p verb prints the address of the slice's first element, that is, the backing array. That address changes when append reallocates.
This is an internal implementation detail that might change in the future.