length and capacity in Go slices

huangapple go评论108阅读模式
英文:

length and capacity in Go slices

问题

假设我们有一个切片b:

b := make([]int, 0, 5) // 长度: 0, 容量: 5

以及由切片b创建的切片"c":

c := b[:2]  // 长度: 2 (?), 容量: 5

问题是为什么切片"c"的长度是2?我原本期望它的长度也是零,就像b一样,因为我们是从b中创建c的。

英文:

Say we have slice of b such

b:= make([]int, 0, 5) // length: 0, cap: 5

and slice of "c" made from slice of "b"

c:= b[:2]  // length: 2 (?), cap: 5

The question if how come we have length of 2 for "c"? I was expecting length of zero as well, like b, since we are making c out of b

答案1

得分: 6

是的,切片操作可以让你访问原始切片长度之外的元素(尽管不能超过其容量,否则可能会访问到未知的内存)。这意味着,例如,你可以实现类似于append的功能,返回一个"增长"了的切片,其长度增加到接近容量的值。也就是说,append对于长度和容量之间的区域的访问不仅仅适用于内置函数,你也可以使用它。在Go博客关于切片的文章中,可以查看Append: an example的示例代码(如果感兴趣,可以阅读整篇文章,有助于更好地理解切片的整体概念)。

切片表达式的规范(以及切片类型)和Slice Tricks页面也可能会很有趣。

英文:

Yep, slicing can get you access to the elements beyond the len of the original slice (though not beyond its cap, or who knows what memory you'd be accessing).

This means, for example, that you can implement append-like functionality, returning a "grown" slice with len increased to something closer to the cap. That is, append's access to the region between len and cap isn't only available to built-in functions; you have it as well. Look at Append: an example in the Go blog entry on slices to see it done (and if interested read the whole post; it helps make slices as a whole make sense).

The spec on slice expressions (and slice types) and the Slice Tricks page may also be interesting.

huangapple
  • 本文由 发表于 2015年12月23日 03:36:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/34423221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定