slice 的創(chuàng)建有兩種方法
test := []int{2,3}
或者是使用make,而且通常我們使用 make創(chuàng)建的情況比較多
例如:
test := make([]int, 5, 5) ? ? ? ? ? ? ? ? ? ? ?// 創(chuàng)建一個類型為 int,長度為 5,容量為 5 的切片
fmt.Println(len(test), cap(test)) ? ? ? ? ?// ?5 5
test1 := make([]int, 3) ? ? ? ? ? ? ? ? ? ? ? ?//如果不指定容量,默認(rèn)容量等于初始時的長度
fmt.Println(len(test1),cap(test1)) ? ? ? ?// 3 3
slice 的長度和容量可以自己是可以動態(tài)改變的, slice 其實(shí)是數(shù)組的某一部分
test := make([]int,0) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 創(chuàng)建一個長度為0,容量為0 的數(shù)組
fmt.Println(len(test),cap(test)) ? ? ? ? ? ? ? // 0 0
test = append(test, 1)
fmt.Println(len(test),cap(test))? ? ? ? ? ? ? // 1 1
test = append(test, 1)
fmt.Println(len(test),cap(test))? ? ? ? ? ? ? // 2 2
test = append(test, 1)
fmt.Println(len(test),cap(test))? ? ? ? ? ? ? // 3 4
當(dāng)數(shù)組的容量不夠時,會重新申請一個兩倍于當(dāng)前長度的 slice,所以在使用過程中,尤其是頻繁去往一個 slice 中 append 數(shù)據(jù),需要盡可能給一個相對準(zhǔn)確的容量, 減少分配過程的損耗。
相關(guān)鏈接: