package main import "fmt" func main() { s := make([]int, 0, 1) oldcap := cap(s) for i := 0; i < 20; i++{ s = append(s, i) if newcap := cap(s); oldcap < newcap { fmt.Printf("oldcap %d ===> newcap %d\n", oldcap, newcap) oldcap = newcap } } }
它的执行结果为:
oldcap 1 ===> newcap 2 oldcap 2 ===> newcap 4 oldcap 4 ===> newcap 8 oldcap 8 ===> newcap 16 oldcap 16 ===> newcap 32
可以看得出来,当一个append执行达到了切片的容量,它会自动扩容为原来的两倍大小