dimanche 12 mars 2017

resizing array with reflect

type Header struct {
    TypeId     int8
    Timestamp  int64
    InstanceId [5]int32
}

I have this type as UDP communication header. But I need InstanceId length can be changeable at runtime. By config file or Env variable. But as stated on golang.com:

An array's size is fixed; its length is part of its type ([4]int and [5]int are distinct, incompatible types)

reflect.ValueOf(&header).Elem().
            FieldByName("InstanceId").
            Set(reflect.New(
                reflect.TypeOf([4]int32{0, 0, 0, 0}),
                ).Elem())

so this code returns

panic: reflect.Set: value of type [4]int32 is not assignable to type [5]int32

I insist on fixed sized array because I plan to use binary.Read() instead of reading fields one by one and binary.Read() doesn't support slices.

Any way around that?





Aucun commentaire:

Enregistrer un commentaire