這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
在Golang語言中,資料類型不多,但是夠用,開發項目過程中,Slice屬於最常用的資料結構之一,對其原理理解不清楚,很容易會遺留bug,筆者查詢了很多部落格資料,對Slice的原理進行一個總結,如果有寫的不清楚不明白之處,請多多包涵,並予以指正。
package mainimport "fmt"func main(){ s := []int{5} s = append(s,7) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0]) s = append(s,9) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0]) x := append(s, 11) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(x) =", &x[0]) y := append(s, 12) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(y) =", &y[0])}
輸出:
cap(s) = 2 ptr(s) = 0x10328008cap(s) = 4 ptr(s) = 0x103280f0cap(s) = 4 ptr(s) = 0x103280f0 ptr(x) = 0x103280f0cap(s) = 4 ptr(s) = 0x103280f0 ptr(y) = 0x103280f0
實際過程:
3ced1eb3dea09f35d7e47410f7403dae_b.jpg
文字說明:
- 建立s時,cap(s) == 1,記憶體中資料[5]
- append(s, 7) 時,按Slice擴容機制,cap(s)翻倍 == 2,記憶體中資料[5,7]
- append(s, 9) 時,按Slice擴容機制,cap(s)再翻倍 == 4,記憶體中資料[5,7,9],但是實際記憶體塊容量4
- x := append(s, 11) 時,容量足夠不需要擴容,記憶體中資料[5,7,9,11]
- y := append(s, 12) 時,容量足夠不需要擴容,記憶體中資料[5,7,9,12]
5中的append是在s的基礎上加入元素12,實際上就是==從s切片的末尾開始寫入==,所以覆蓋掉了11