Reputation: 958
I'm rather new with go and I'm trying to access a portion of a byte slice and copy to a another fixed length byte slice but doesn't find the proper solution.
My best bet was :
var extracted []byte
var newSlice [512]byte = extracted[0 : 511]
But this gives me a conversion error :
cannot use extracted[0:511] (value of type []byte) as [512]byte value in variable declarationcompilerIncompatibleAssign
Notes :
I thought I could use a io.Reader but this approach failed miserably as well.
Any help welcome :)
Upvotes: 0
Views: 329
Reputation: 121149
Here are a couple of approaches:
Convert the slice to an array pointer and dereference that pointer:
var pixels [512]byte
pixels = *(*[512]byte)(extracted[:512])
This can be done in one statement using a short variable declaration:
pixels := *(*[512]byte)(extracted[:512])
Use the builtin copy function to copy elements from a slice to an array (this point was covered in the question comments):
var pixels [512]byte
copy(pixels[:], extracted[:512])
Upvotes: 1