Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Slicing a byte array to conform to a struct for param in Golang?

I have something roughly like this

type Guid [16]byte

type Payload struct {
    ....
    SthGuid  [17]byte
}


func (h *...) Get(guid Guid) (... error) {

}

and I want to call Get with the last 16 bytes of SthGuid. E.g.,

Get(PayloadInstance.SthGuid[1:16]))

cannot convert SthGuid[1:16] (value of type []byte) to Guid

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m trying to call SthGuid[1:] to slice the first byte and use the last 16 bytes as an input param. Doesn’t work that way.

>Solution :

You can do copying of array with right type, e.g:

var guid [16]byte
copy(guid[:], SthGuid[1:16])
Get(guid)

or, as a Go 1.17 you can try to use array casting:

https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading