美文网首页
What the official tutorial didn'

What the official tutorial didn'

作者: 邪恶的奥伯伦 | 来源:发表于2019-10-28 11:30 被阅读0次

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]并没有移动指针

mwulG.png p2eqp.png 7GnUF.png

这也解释了为什么执行slice执行s[:2]操作会减少该slice的capacity而s[:4]却不会改变capacity.

reference(https://stackoverflow.com/questions/43294449/decreasing-slice-capacity

相关文章

网友评论

      本文标题:What the official tutorial didn'

      本文链接:https://www.haomeiwen.com/subject/digvvctx.html