type slice struct {
array unsafe.Pointer
len int
cap int
}
var slice []int
var array [n]int // [...]int{1, 2, 3}
make([]byte, 5)
s = s[2:4]
Go Slices: usage and internals
Initialization
s1 := make([]int32, 0, 5)
s2 := []int32{1, 2, 3}
s3 := *new([]int32)
A slice created with make
always allocates a new, hidden array to which the returned slice value refers. And make([]T, length, capacity)
produces the same slice as allocating an array and slicing it, so these two expressions are equivalent:
make([]int, 50, 100)
new([100]int)[0:50]
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.
To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it.
从数组创建切片
a[low : high]
selects a half-open range which includes the first element, but excludes the last one.
[:]
allows u to create a slice from an array, optionally using start and end bounds.
a := [3]int{1, 2, 3, 4} // "a" has type [4]int (array of 4 ints)
x := a[:] // "x" has type []int (slice of ints) and length 4
y := a[:2] // "y" has type []int, length 2, values {1, 2}
array[x:y:z]
切片实体 [x:y]
切片长度 len = y-x
切片容量 cap = z-x
data := [...]int{0, 1, 2, 3, 4, 5, 6} // 初始化数组
slice := data[1:4:5] // [low:high:max] 创建切片
slice 长度为 3 索引从 1 到 3 的数据 {1, 2, 3} 容量为 4 底层数组为 [1, 2, 3, 4]