The built-in append () function appends an item to slice. If the slice also has free capacity (Cap (s) > len (s)), it is appended directly. Otherwise, the slice is expanded before being appended. These are detailed in the documentation for the Append () function, but the document does not say how the expansion is done, so the following is an experiment with a piece of code:
Package Main
func main () {
s: = []int{}; println (Cap (s))//0
s = Appendn (s, 1); println (Cap (s))//2
s = APPENDN (S, 2); println (Cap (s))//4
s = Appendn (S, 4), println (Cap (s))//8
s = APPENDN (S, 8); println (Cap (s))//+
s = AppE NdN (S, 16); println (Cap (s))//+
s = Appendn (s, +), println (Cap (s))//
s = Appendn (s, +), println (Cap (s))//
s = []int{1,2,3}; println (Cap (s))//3
s = Appendn (S, 2), println (Cap (s))//8
}
func appendn (s []int, n int) []int {
fo R I: = 0; I < n; i++ {
s = append (s, 0)
}
return s
}
It can be seen that, at least for the above code, the capacity is not simply growing enough to accommodate the new item each time it needs to be scaled up, but is further expanded to 2n