一般切片表達式:
numbers := [10]int{0,1,2,3,4,5,6,7,8,9}
s := numbers[1:4]
fmt.Println(s) // [1, 2, 3]
fmt.Println(cap(s)) // 9
完整切片表達式:
numbers := [10]int{0,1,2,3,4,5,6,7,8,9}
s := numbers[1:4:5]
fmt.Println(s) // [1, 2, 3]
fmt.Println(cap(s)) // 4
input[low:high:max]
其中low 和 high 和一般切片表達式的用法一樣,那麼運算後的切片cap爲:max — low
例如:
numbers := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(cap(numbers)) // 10
s1 := numbers[1:4]
fmt.Println(s1) // [1, 2, 3]
fmt.Println(cap(s1)) // 9
s2 := numbers[1:4:5]
fmt.Println(s2) // [1, 2, 3]
fmt.Println(cap(s2)) // 4
s3 := s2[:]
fmt.Println(s3) // [1, 2, 3]
fmt.Println(cap(s3)) // 4
完整切片的巧妙用法:
p := append(t[:0:0], t...)
相當於:
p := make([]int,len(t))
copy(p,t)
參考資料:
https://medium.com/golangspec/slice-expressions-in-go-963368c20765