Golang Slice
slice 新增时 len+1 超出 cap 触发扩容,每次触发扩容,新分配的数组容量增加一倍(cap = 0 时,扩容新增 1,之后都是翻倍),扩容后,指针会指向新的数组
func TestModifySlice(t *testing.T) {
var s []int // 初始 cap = 0
for i := 0; i < 3; i++ {
// zlen = len + 1 > cap, 触发数组 copy
// len = 0, zlen = len + 1 = 1 > cap = 0 => zcap = zlen = 1, if zcap = 1 < 2*len = 0 { zcap = 2*len }; cap = zcap = 1
// len = 1, zlen = len + 1 = 2 > cap = 1 => zcap = zlen = 2, if zcap = 2 < 2*len = 2 { zcap = 2*len }; cap = zcap = 2
// len = 2, zlen = len + 1 = 3 > cap = 2 => zcap = zlen = 3, if zcap = 3 < 2*len = 4 { zcap = 2*len = 4 }; cap = zcap = 4
// ------ 分割线 -------
// len = 3, zlen = len + 1 = 4 == cap = 4
// len = 4, zlen = len + 1 = 5 > cap = 4 => zcap = zlen = 5, if zcap = 5 < 2*len = 8 { zcap = 2*len = 8 }; cap = zcap =8
s = append(s, i)
}
modifySlice(s)
fmt.Println(s)
}
// 1024, 1, 2
func modifySlice(s []int) {
s[0] = 1024
}
// 1024, 1, 2
func modifySlice(s []int) {
s = append(s, 2048)
s[0] = 1024
}
// 0, 1, 2
func modifySlice(s []int) {
s = append(s, 2048)
s = append(s, 4096)
s[0] = 1024
}