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

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

问题描述

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

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]

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

Invoking cap on numSlice and nums yields 3 in both cases, and len yields 2 and 3 respectively.

如果我然后附加到该切片 (numSlice = append(numSlice, 10)),则底层数组 (nums) 现在是 [1 2 10].cap 两者都保持为 3,因为切片的底层数组是相同的,切片的 len 现在为 3.

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.

但是,如果我再次追加到该切片 (numSlice = append(numSlice, 20)),则切片的底层数组必须更改 - 我们看到 cap 时的情况 现在 numSlice 增加了一倍,len 现在是 4.

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.

现在要访问底层数组,可以结合使用reflect不安全.特别是,reflect.SliceHeader 包含一个 Data 字段包含一个指向切片底层数组的指针.

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.

示例改编自 unsafe 包的文档:

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天全站免登陆