mardi 10 mars 2015

How can I create slice of struct with reflection in Go

I need to create a slice of struct from its interface with reflection.


I used Reflection because do not see any other solution without using it.


Briefly, the function receives variadic values of Interface.


Then, with reflection creates slice and passes it into another function.


Reflection asks to type assertion



SliceVal.Interface().(SomeStructType)


But, I cannot use it.


Code in playground http://ift.tt/187mdnN


The code:



package main

import (
"fmt"
"reflect"
)

type Model interface {
Hi()
}

type Order struct {
H string
}

func (o Order) Hi() {
fmt.Println("hello")
}

func Full(m []Order) []Order{
o := append(m, Order{H:"Bonjour"}
return o
}

func MakeSlices(models ...Model) {
for _, m := range models {
v := reflect.ValueOf(m)
fmt.Println(v.Type())
sliceType := reflect.SliceOf(v.Type())
emptySlice := reflect.MakeSlice(sliceType, 1, 1)
Full(emptySlice.Interface())
}
}
func main() {
MakeSlices(Order{})
}





Aucun commentaire:

Enregistrer un commentaire