golang slice 創(chuàng)建

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)鏈接:

切片的復(fù)制與追加

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容