在Go语言中,可以通过切片来获取数组。

huangapple go评论93阅读模式
英文:

Obtain array from slice in Go (language)

问题

如果我使用以下代码创建一个切片:

mySlice := make([]int, 5, 10)

那么我认为会隐式地创建一个类型为[10]int的数组,并且我会得到一个能够“看到”前5个整数的切片。

(对吗?Go文档没有完全这样表述,但由于切片必须始终在某个地方有一个底层数组,我不知道还有其他的方式。)

所以我相信上述代码是以下代码的简写形式:

var myArray [10]int
mySlice := myArray[0:5]

但是当我使用第一种方法时,我没有数组的句柄。有没有办法从切片中获取它呢?

英文:

If I create a slice with (e.g.)

mySlice := make([]int, 5, 10)

then I suppose an array of type [10]int is created silently, and I receive a slice that "sees" the first 5 ints.

(Right? The Go docs don't quite phrase it this way, but since a slice must always have an underlying array somewhere, I don't see how it could be any other way.)

So I believe the above is shorthand for:

var myArray [10]int
mySlice := myArray[0:5]

But when I use the first method, I don't have a handle to the array. Is there any way to obtain it from the slice?

答案1

得分: 3

不使用不安全的指针技巧,无法从切片中获取数组。

英文:

Without using unsafe pointer tricks, there's no way how to get an array from a slice.

答案2

得分: 2

我不确定你想要什么样的“句柄”,但在Go语言中,数组是按值传递的。所以如果你有一个接受数组作为参数的函数,你可以将切片中的数据复制到一个数组中,然后传递这个数组。当你将数组传递给函数时,它会被复制。

如果是你自己的代码想要使用数组,它可以通过切片来完成与数组相同的操作。

唯一不能使用unsafe包完成的操作是创建指向数组的指针,但你可以使用unsafe包轻松实现:

arrayPtr := (*[10]int)(unsafe.Pointer(&mySlice[0]))
英文:

I'm not sure what kind of "handle" you want, but arrays are passed by value in Go. So if you have a function that takes an array as a parameter, you can just copy the data from the slice into an array, and pass the array. The array would be copied anyway when you passed it to the function.

If it's your own code that wants to work with the array, it can do everything with the slice that it would with the array.

The only thing you can't do without unsafe is to create a pointer to the array—but you can do that easily with unsafe:

arrayPtr := (*[10]int)(unsafe.Pointer(&mySlice[0]))

huangapple
  • 本文由 发表于 2013年8月31日 23:03:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/18549500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定