The Go Programming Language Specification
Appending to and copying slices
If the capacity of s is not large enough to fit the additional values,
append allocates a new, sufficiently large underlying array that fits
both the existing slice elements and the additional values. Otherwise,
append re-uses the underlying array.
For additional details on how the append
built-in function works, read this blog post:
Arrays, slices (and strings): The mechanics of 'append'
Also, see this StackOverflow answer, which illustrates the reallocation capacity calculation:
append
complexity
For example,
package main
import "fmt"
func main() {
orgArray := [3]string{"00", "01", "02"}
fmt.Println("orgArray:", &orgArray[0], len(orgArray), orgArray)
s := orgArray[:2]
fmt.Println(" s:", &s[0], len(s), cap(s), s)
s = append(s, "03")
fmt.Println(" s:", &s[0], len(s), cap(s), s)
s = append(s, "04")
fmt.Println(" s:", &s[0], len(s), cap(s), s)
fmt.Println("orgArray:", &orgArray[0], len(orgArray), orgArray)
}
Output:
orgArray: 0x1052f2c0 3 [00 01 02]
s: 0x1052f2c0 2 3 [00 01]
s: 0x1052f2c0 3 3 [00 01 03]
s: 0x1051a120 4 6 [00 01 03 04]
orgArray: 0x1052f2c0 3 [00 01 03]