doucan9079 2013-07-27 19:13
浏览 22
已采纳

append()是否总是扩展所需的最小容量?

When learning slice, I have this doubt: does append() always extend minimal capacity needed?

a := make([]byte, 0)
a = append(a, 1, 2, 3)
cap(a) == 3  // will this be always true?
// or the assumption may not hold since the underlying implementation of append()
// is not specified.
  • 写回答

2条回答 默认 最新

  • dongzhang4301 2013-07-27 19:41
    关注

    No, it's not guaranteed in this case. The specifications say:

    append(s S, x ...T) S  // T is the element type of S
    

    If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large slice that fits both the existing slice elements and the additional values. Thus, the returned slice may refer to a different underlying array.

    (Emphasizes mine)

    In your case, clearly any capacity >= 3 is sufficiently large, so you can rely on cap >= 3, but you cannot rely on cap == 3.

    Of course you can assume cap in this case will not be, say 1e6 or 1e9 or 1e12. However, the exact enlarging (allocating new backing array) strategy is intentionally not specified in every detail to allow the compiler guys to experiment with some knobs attached to this mechanism.

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

报告相同问题?