How to create a slice structure with reflection in Go

I need to create a slice of the structure from its reflection interface.

I used Reflection because I cannot see another solution without using it.

In short, a function gets the variable values ​​of an interface.

Then, when the reflection creates a slice and passes it to another function.

Reflection asks for approval type

SliceVal.Interface().(SomeStructType) 

But I can’t use it.

Code on the playground http://play.golang.org/p/EcQUfIlkTe

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{}) } 
+6
source share
1 answer

You are almost there. The problem is that you do not need to inject type-assert into the structure type, but into the slice type.

So instead

 SliceVal.Interface().(SomeStructType) 

You should:

 SliceVal.Interface().([]SomeStructType) 

And in your specific example - just changing the next line makes your code work:

 Full(emptySlice.Interface().([]Order)) 

Now, if you have many possible models, you can do the following:

 switch s := emptySlice.Interface().(type) { case []Order: Full(s) case []SomeOtherModel: FullForOtherModel(s) // etc } 
+3
source

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


All Articles