33

golang的slice

 5 years ago
source link: https://studygolang.com/articles/18153?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

声明与定义

Go中的slice的声明方法(有时候顺便也定义了),主要分为下面几种(以int为例):

[]int

后面可以也可以不跟上初始值,如

[]int
[]int {}
[]int {1,2,3}

另外,直接从数组或者slice中再建立slice也是一种常见的模式:

c[l:h:c]

最后一种是通过make来创建:

make([]int, len, cap)

其中len,cap都是可选的,如果没有cap,缺省就是len那么大,如果没有len,缺省就是0。

添加

内置函数append是范型的添加,可以添加一个或者多个元素,也可以直接添加另外一个slice,这时候,需要使用 ... 运算符进行解包,如:

append(a, [] int {1,2,3}...)

不常用但是有时候也有用的,就是在slice的头部添加元素,象这样:

append([]int{1,2,3}, a)

头部添加开销一般比较大,需要移动元素甚至重新分配内存。

空slice与nil slice

空slice是len与cap都为0的slice,而nil slice则没有指向一个对象,这两者是有区别的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK