如何在Go中获得切片的底层数组? [英] How to get the underlying array of a slice in Go?

查看:792
本文介绍了如何在Go中获得切片的底层数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有下面的长度为3的整数数组:

nums:= [3] int {1,2,3 }然后,我抓住了前两项的片段。



$ b

code> numSlice:= nums [:2]



调用 cap 对于numSlice和nums,在两种情况下都会产生3,而 len 分别产生2和3.

numSlice = append(numSlice,10)),底层数组( nums )现在是 [1 2 10] cap 对于两者都保持为3,因为切片的底层数组是相同的,并且切片的len现在为3。



但是,如果我再次追加到该片( numSlice = append(numSlice,20)),片的底层数组必须改变 - 我们看到这个当$ cap 现在已经为numSlice加倍并且len现在为4时。



对于过度解释,只是走过自己,但有人可以向我解释底层数组的底层底下发生了什么,以及如何获得对新数组的引用? 首先,如果你还没有,你应该阅读这篇关于分片内部的官方博客文章。这应该清除一切。



现在访问底层数组,您可以使用 反映 不安全 。特别是, reflect.SliceHeader 包含 Data 字段,其中包含指向切片底层数组的指针。

不安全包:

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


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?

解决方案

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))

这篇关于如何在Go中获得切片的底层数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆