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
source share