Golang ¶
slice 太多了,分成兩篇
9. Slice ¶
The type
[]Tis a slice with elements of typeT
The zero type of slice is
nil
Slice like a reference to array, so it does not store any data
Slice 像是指向 array 的 reference
names[0:2] 是從第 0 個 element 開始(包括在裡面),一直到第 2 個 element 結束(不包括在裡面)
names := [4]string{
"Emma",
"AAA",
"Alice",
"dlwlrma",
}
fmt.Println(names)
a := names[0:2]
b := names[1:3]
fmt.Println(a, b)
b[0] = "XXX"
fmt.Println(a, b)
fmt.Println(names)
// Result
[Emma AAA Alice dlwlrma]
[Emma AAA] [AAA Alice]
[Emma XXX] [XXX Alice]
[Emma XXX Alice dlwlrma]
注意看,Slice 裡的 value 被改變,array 裡的 value 也會被改變
在宣告時,dlwlrma 後面還有一個 ,
slice length and capacity ¶
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
s = s[:5]
printSlice(s)
func printSlice(s []int){
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
// Restult
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
panic: runtime error: slice bounds out of range
可以看得出來 s = s[:0] 並沒有把 capacity 減少,只有減少長度
所以 s = s[:4] 才能到 4,這個 statement 也是在 extend slice 的 length
但是 s = s[2:] drop first two elements,capacity 只剩下 4
所以 s = s[:5] 無法到 5,因為長度不夠,就跳 error 了
所以說 length 就是長度但是不能超過 capacity ¶
而 capacity 就是這個 slice 最多可以容納多少值 ¶
Create slice with make ¶
function : make([]T, length, capacity)
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[:2]
printSlice("c", c)
d := c[2:5]
printSlice("d", d)
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n", s, len(x), cap[x], x)
}
// Result
a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
c len=2 cap=5 [0 0]
d len=3 cap=3 [0 0 0]
可以傳入兩個參數也可以傳入三個參數
這裡要注意的是 c := b[:2] 這個 statement 會成立是因為是在 extend 長度,所以只要不要超過 capacity 就好了
但是如果是寫在前面就是要 drop elements,可是現在 slice 裡面沒有 elements 可以 drop,所以會 error
It can be passed for two or three arguments.
We need to mention that the statement c := b[:2] can be succeeded because it extends the lenghth of slice
Therefore, do not over the capacity is the only thing need to worry.
However, if the statement is c := b[1:], it menas that drop the first elements, but the slice does not have elements to drop, becaues the length is 0.
As a result, it will be error.
Appending the slice ¶
增加 slice 的 capacity
append(s []T, vs ...T) []T
slice = append(slice, elem1, elem2)
slice = append(slice, another slice...)
var s []int
printSlice(s)
s = append(s, 0)
printSlice(s)
s = append(s, 1)
printSlice(s)
s = append(s, 2, 3)
printSlice(s)
s = append(s, 4, 5, 6)
printSlice(s)
s = append(s, cap(s))
printSlice(s)
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
//Result
len=0 cap=0 []
len=1 cap=2 [0]
len=2 cap=2 [0 1]
len=4 cap=4 [0 1 2 3]
len=7 cap=8 [0 1 2 3 4 5 6]
len=8 cap=8 [0 1 2 3 4 5 6 0]
這裡需要注意的是 capacity 是 0 -> 2 -> 4 -> 8 倍數增長的
先這樣吧
最近懶懶散散的,可能放假太久的原因