-2

I recently studying go in w3schools and I can't able to understand capacity of slice in go? How the cap() of myslice1 is 12.Slice in go

I expect that the cap() of myslice1 is 8 because I append the two numbers on previously created slice.But the cap() myslice1 before append is 6. And after appended the cap()of myslice is 12.

Marco
  • 2,371
  • 2
  • 12
  • 19
  • 3
    Please include *code*, not *images of code*: see [*Why not upload images of code errors when asking a question*](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). [edit] the question and include code fragments with the *code sample* button (`{}`). – Willem Van Onsem Aug 27 '23 at 17:01

1 Answers1

1

The Go Programming Language Specification

Appending to and copying slices

If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array.


Your expectations are not correct. The capacity will be sufficiently large. The exact amount of a capacity increase is implementation defined and depends on a number of factors. Implementations typically use amortized time algorithms.

rocka2q
  • 2,473
  • 4
  • 11