Whoever follow the Golang official tutorial about Slice
the array(https://tour.golang.org/moretypes/11) may have a doubt about 为什么slice第一个参数会把前面两个参数直接remove掉了,
官方教程在这里并没有解释清楚, 这其实是因为slice为了执行效率并没有copy一份原始array 数据, 仅仅是一个指向第一个数据的指针。
当执行类似 s[2:]的操作, 该slice的指针会移动到第三个值的位置,所以前面两个值无法再次通过该slice访问, 但是slice操作却可以重新恢复后面的参数 通过扩充的方式 s[:4]
这是因为slice[2:]移动了指针, 而s[:4]并没有移动指针
![](https://img.haomeiwen.com/i5900426/7931613d11aadcdd.png)
![](https://img.haomeiwen.com/i5900426/c4a2b2a0293e1a5f.png)
![](https://img.haomeiwen.com/i5900426/319efb04facb08d7.png)
这也解释了为什么执行slice执行s[:2]操作会减少该slice的capacity
而s[:4]却不会改变capacity
.
reference(https://stackoverflow.com/questions/43294449/decreasing-slice-capacity)
网友评论