slice,是go中一個很重要的主題。咱們不用切片來表述,由於這裏的切片特指的是數組的切片。express
Slice expressions construct a substring or slice from a string, array, pointer to array, or slice. There are two variants: a simple form that specifies a low and high bound, and a full form that also specifies a bound on the capacity.數組
從一個字符串中構建了一個子字符串或者從一個數組中構建一個切片,而且把這個子字符串或是這個切片的指針賦給這個slice.換句話說slice就是指向某個字符串或者某個數組的一個指針。指針
表面上來看,slice是一種與array很類似的東西,可是二者之間最大的區別是array是定長的而slice能夠更改其長度。code
a[low : high]
建立一個數組orm
a := [5]int{1, 2, 3, 4, 5}索引
建立切片ci
s := a[1:4]字符串
slice s中元素的類型是int,length(長度)是3(high-low),capacity(容量)是4string
(原文呈現)For convenience, any of the indices may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand。(爲了方便,任何索引都是能夠被忽略的,開始的索引默認爲0,結束的索引默認爲slice的長度)it
a[2:] // same as a[2 : len(a)] a[:3] // same as a[0 : 3] a[:] // same as a[0 : len(a)]
slicer := make([]int, 10)
能夠經過make來新建一個slice,第一個參數是slice中的元素類型,第二個參數是這個slice的容量。
當咱們建立了一個slice的時候會發生如下的事情:
建立了一個與參數1相匹配元素類型的、參數2長度的數組。
建立指向這個數組的指針並賦給這個切片。
這裏的指針其實就是指向了slice索引值start值對應的數組元素的位置的地址。
func main() { a := [5]int{1, 2, 3, 4, 5} var d *[5]int = &a println(d) println(a[0:4]) println(a[1:4])}
結果:
0x220822bf08//原始數組地址 [4/5]0x220822bf08//對應切片a[0:4]地址 [3/4]0x220822bf10//對應切片a[1:4]地址