How to get the underlying array of a slice in Go?

﹥>﹥吖頭↗ 提交于 2019-12-04 10:31:21

问题


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?


回答1:


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 and unsafe. In particular, reflect.SliceHeader contains a Data field which contains a pointer to the underlying array of a slice.

Example adapted from the documentation of the unsafe package:

s := []int{1, 2, 3, 4}
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
data := *(*[4]int)(unsafe.Pointer(hdr.Data))


来源:https://stackoverflow.com/questions/36706843/how-to-get-the-underlying-array-of-a-slice-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!