Let's say I have the following array of ints of length 3:
nums := [3]int{1,2,3}
Then I grab the slice of just the first two items
numSlice := nums[:2]
Invoking cap
on numSlice and nums yields 3 in both cases, and len
yields 2 and 3 respectively.
If I then append to that slice (numSlice = append(numSlice, 10)
), the underlying array (nums
) is now [1 2 10]
. cap
remains at 3 for both, as the underlying array of the slice is the same, and len for the slice is now 3.
However, if I append to that slice again (numSlice = append(numSlice, 20)
), the underlying array of the slice must change – we see this is the case when cap
now has doubled for numSlice and len is now 4.
Sorry for the overwrought explanation, just walking myself through it, but can someone explain to me what happens under the hood to the underlying array and how to get the reference to the new array?
Best Answer
First, if you haven't already, you should read this official blog post about slice internals. That should clear up everything.
Now to access the underlying array, you can use a combination of
reflect
andunsafe
. In particular,reflect.SliceHeader
contains aData
field which contains a pointer to the underlying array of a slice.Example adapted from the documentation of the
unsafe
package: