dsjbest2014 2016-07-23 16:13
浏览 83
已采纳

将一个元素附加到零切片将容量增加两个

I have a nil slice:

var s1 []int // len(s1) == 0, cap(s1) == 0

Which I append one element to:

s2 := append(s1, 1) // len(s2) == 1, cap(s2) == 2

Why is appending one element to a nil slice increases the capacity by 2?

Printing the slices using fmt.Printf shows the following:

[] // s1
[1] // s2

I am also confused about why re-slicing s2[0:2] shows a zero which was not in the original slice nor appended to it:

[1,0] // s2[0:2]
  • 写回答

4条回答 默认 最新

  • dsfsda121545 2016-07-23 16:47
    关注

    Go is free to provide you more capacity than you request. This improves performance by reducing the number of allocations (and possibly copying) that are required. Capacity is just the amount of space reserved before another allocation would be required.

    If you append 5 elements to this slice, at least in my experiments, the capacity is 8. This shouldn't be surprising, but also shouldn't be relied on. On different platforms, or different versions of the compiler, the actual result may be different, as long as the capacity is "sufficiently large" (equal to or greater than length).

    The upper index bound of a slice is defined as its capacity:

    For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length. A constant index must be non-negative and representable by a value of type int; for arrays or constant strings, constant indices must also be in range. If both indices are constant, they must satisfy low <= high. If the indices are out of range at run time, a run-time panic occurs.

    This is why reading past the length is not causing a panic. Even so, you shouldn't think of those zeros as part of the slice. They are indexable by the slice, but fmt.Printf(s2) would correctly not show them because they are not part of the slice. Don't subscript this way.

    In general, you want to be looking at length, not capacity. Capacity mostly is readable to assist in performance optimization.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败