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

99封情书 提交于 2019-12-03 05:17:22

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