Decreasing slice capacity

前端 未结 1 1639
生来不讨喜
生来不讨喜 2021-02-07 00:04

My question is about slice length and capacity. I\'m learning about Go here: https://tour.golang.org/moretypes/11.

(My question was marked as a possible duplicate of thi

1条回答
  •  野性不改
    2021-02-07 00:28

    You can read more about slices here. But I think this passage answers your question:

    Slicing does not copy the slice's data. It creates a new slice value that points to the original array. This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice.

    So you cannot recover the slice data if you are assigning it to the same variable.

    The capacity decrease is because by dropping the first 2 elements you are changing the pointer to the new slice (slices are referenced by the pointer to the first element).

    How slices are represented in the memory:

    make([]byte, 5)
    

    s = s[2:4]
    

    0 讨论(0)
提交回复
热议问题