Reputation: 71
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?
Upvotes: 2
Views: 222
Reputation: 16100
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]))
Upvotes: 2
Reputation: 91203
Without using unsafe pointer tricks, there's no way how to get an array from a slice.
Upvotes: 3