samedi 12 mars 2016

Copying a slice into a reflected array

I have a structure that looks like this:

type Record struct {
   Name         string
   QuestionType [2]byte // Array may be arbitrary length
   Class        [2]byte
}

I am attempting to fill the structure with bytes from a bytes.Buffer (I am unable to use binary.Read due to some additional complexity in the byte data.) I'm using the reflect package to iterate over the elements of the structure, and read from the bytes.Buffer into the structure.

func fillStructure(buffer *bytes.Buffer) *Record {
   // This is hard-coded now, but will be passed in as an interface later
   myStruct := Record{}
   reflectedStruct := reflect.ValueOf(&myStruct).Elem()

   for i := 0; i < reflectedStruct.NumField(); i++ {
      field := reflectedStruct.Field(i)

      if field.Kind() == reflect.Array {
         // Copy bytes from buffer into structure
      }
   }

   return &myStruct
}

However, when I attempt to fill the [2]byte arrays with 2 bytes from the buffer, I find myself unable to copy the slice returned by buffer.Next(2) into the array in the struct.

  • field.Set() doesn't work because []byte is incompatible with [2]byte.
  • copy() doesn't work because I can't find a way to get a slice of the struct's array

Question: Is there a way to get a slice "view" of the reflected structure's array so I can copy the values in? Or some other way to copy the slice returned by buffer into the structure?





Aucun commentaire:

Enregistrer un commentaire