lundi 7 novembre 2016

reflect.Set slice-of-structs value to a struct, without type assertion (because it's unknown)

I'm creating a helper package to pop payloads from a queue. It's essential that this helper be agnostic to the struct used by the application importing it.

This (no-op, just example) function will provide a single payload from the queue, of the provided type like interface{}:

func One(like interface{}) interface{} {
    typ := reflect.TypeOf(like)
    one := reflect.New(typ)

    return one.Interface()
}

This function provides many payloads:

func Many(num int, like interface{}) interface{} {
    typ := reflect.TypeOf(like)
    many := reflect.MakeSlice(reflect.SliceOf(typ), num, num)

    for i := 0; i < num; i++ {
        one := One(typ)
        many.Index(i).Set(one)
    }

    return many.Interface()
}

An example of usage is:

type Payload struct {
    Id int
    Text string
}

func main() {
    Many(4, Payload{})
}

However, the above results in:

panic: reflect.Set: value of type **reflect.rtype is not assignable to type main.Payload

See: http://ift.tt/2ePpEnh





Aucun commentaire:

Enregistrer un commentaire