7

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://play.golang.org/p/EcQUfIlkTe

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{})
}

1 Answer 1

4

You're almost there. The problem is that you don't need to type-assert to the struct type, but to the slice type.

So instead of

SliceVal.Interface().(SomeStructType)

You should do:

SliceVal.Interface().([]SomeStructType)

And in your concrete example - just changing the following 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
}
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, I appreciate this ansert. as the funtion receives variadic variables, how can I set type assertion when I do not know which struct slice is being created?
@user2660766 How can you call Full for a specific type if you have many possible types? You can simply do a type switch and call a separate function for each possible model.
It was just example function for test
@user2660766 see my expanded answer, I've added an exmaple on how to route to multiple functions based on the model
Any ideas on how this might work without actually knowing the struct type to assert? stackoverflow.com/questions/40474682/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.