Home > Software engineering >  Slicing a byte array to conform to a struct for param in Golang?
Slicing a byte array to conform to a struct for param in Golang?

Time:01-28

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

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.

CodePudding user response:

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 slice to array conversion:

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

  •  Tags:  
  • Related