錯誤代碼
func TestSliceGrowing(t *testing.T) {s := [4]int{1, 2, 3, 4}for i :=0; i<10; i++ {s = append(s, i)t.Log(len(s), cap(s))}
}
報錯代碼
s = append(s, i)
原因:append的第一個參數必須是切片
更正
func TestSliceGrowing(t *testing.T) {s := []int{1, 2, 3, 4}for i :=0; i<10; i++ {s = append(s, i)t.Log(len(s), cap(s))}
}
cap 的值在初始化的時候,如果切片沒有初始值,則為1,如果有初始值,如上,則為元素個數len,在執行append后,如果len超過cap,則cap值變為原來的兩倍。
func TestSliceCap(t *testing.T) {arr := [5]int{1, 2, 3, 4, 5}s := arr[:2]t.Log(len(s), cap(s))
}
len :2, cap 5
cap = arr length - start index
我的公眾號