Byte slice partial copy

Viewed 45

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 :

  • this will be in a loop to iterate over the entire size of extracted 512 bytes at a time;
  • extracted actually has a fixed size of 512*n bytes, but if I fix that length I have the same issue

I thought I could use a io.Reader but this approach failed miserably as well.

Any help welcome :)

1 Answers

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