Reflect.Set slice-of-struct value for the structure, without a type statement (since it is unknown)

I am creating a helper package for loading payload data from a queue. It is very important that this assistant is an agnostic for the structure used by the application importing it.

This function (no-op, just example) 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 feature 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() } 

Usage example:

 type Payload struct { Id int Text string } func main() { Many(4, Payload{}) } 

However, the above results:

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

https://play.golang.org/p/ud23ZlD3Bx

0
source share
1 answer

You call reflect.TypeOf on reflect.Value , where **reflect.rtype comes **reflect.rtype .

Call the One function with the like value directly and assign this result to the slice.

 func One(like interface{}) interface{} { typ := reflect.TypeOf(like) one := reflect.New(typ) return one.Interface() } 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(like) many.Index(i).Set(reflect.ValueOf(one).Elem()) } return many.Interface() } 

https://play.golang.org/p/fHF_zrymcI

+2
source

Source: https://habr.com/ru/post/983587/


All Articles