Go 語言切片是對數組的抽象。
Go 數組的長度不可改變,在特定場景中這樣的集合就不太適用,Go中提供了一種靈活,功能強悍的內置類型切片("動態數組"),與數組相比切片的長度是不固定的,可以追加元素,在追加時可能使切片的容量增大。
定義方式:
~~~
1) make ( []Type ,length, capacity )
2) make ( []Type, length)
3) []Type{}
4) []Type{value1 , value2 , ... , valueN }
~~~
從3)和4)可見,創建切片跟創建數組唯一的區別在于 Type 前的"[]"中是否有數字或....,沒有表示切片,否則表示數組。
## 一、示例
~~~
package main
import (
"fmt"
)
func main() {
slice1 := make([]int32, 5, 8)
slice2 := make([]int32, 9)
slice3 := []int32{}
slice4 := []int32{1, 2, 3, 4, 5}
fmt.Println(slice1)
fmt.Println(slice2)
fmt.Println(slice3)
fmt.Println(slice4)
}
~~~
結果:
~~~
[0 0 0 0 0]
[0 0 0 0 0 0 0 0 0]
[]
[1 2 3 4 5]
~~~
## 二、append()追加元素
~~~
package main
import (
"fmt"
)
func main() {
slice := []int32{}
slice = append(slice, 1, 2, 3)
fmt.Println(slice, "長度:", len(slice), "容量:", cap(slice))
}
~~~
結果:
~~~
[1 2 3] 長度: 3 容量: 4
~~~
## 三、切片(索引從0開始,包左不包右)
~~~
numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println(numbers[1:4]) // >=1 && <4
fmt.Println(numbers[:3]) // <3
fmt.Println(numbers[4:]) // >=4
~~~
結果:
~~~
numbers[1:4] == [1 2 3]
numbers[:3] == [0 1 2]
numbers[4:] == [4 5 6 7 8]
~~~
## 四、copy()復制
~~~
numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8}
numbers2 := []int{}
copy(numbers2, numbers) // 把numbers復制到numbers2
fmt.Println(numbers2)
~~~
結果:
~~~
numbers2 == [0 1 2 3 4 5 6 7 8]
~~~