切片的容量是原来的2倍方式增长的
例子
package main
import "fmt"
func main() {
s := make([]int, 3, 6) //len == 3, cap == 6
fmt.Println("i ", "len", "cap")
for i := 0; i < 17; i++ {
s = append(s, i)
fmt.Printf("%-3d %-3d %-3d\n", i, len(s), cap(s))
}
}
结果
i len cap
0 4 6
1 5 6
2 6 6
3 7 12 <---cap不够了,分配原来的2倍
4 8 12
5 9 12
6 10 12
7 11 12
8 12 12
9 13 24 <---cap不够了,分配原来的2倍
10 14 24
11 15 24
12 16 24
13 17 24
14 18 24
15 19 24
16 20 24