Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Slice from Reflected Type

I am trying to create a slice from a reflect.Type. This is what I have so far.

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.New(reflect.SliceOf(elemType)).Interface()

    elemSlice = append(elemSlice, TestStruct{"Testing"})

    fmt.Printf("%+v\n", elemSlice)

}

However I get the following error and I'm not sure how to get around it without hardcoding a conversion to []TestStruct.

prog.go:17: first argument to append must be slice; have interface {}

Is there anyway to treat the returned interface as a slice without having to hardcode the conversion from interface{} to []TestStruct?

like image 580
moesef Avatar asked Aug 07 '16 21:08

moesef


1 Answers

No, what you describe is not possible. Not type asserting the result of .Interface() limits what you can do. Your best chance is to continue to work with the reflect.Value value:

package main

import (
    "fmt"
    "reflect"
)

type TestStruct struct {
    TestStr string
}

func main() {
    elemType := reflect.TypeOf(TestStruct{})

    elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)

    elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))

    fmt.Printf("%+v\n", elemSlice)

}

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

like image 160
Tim Cooper Avatar answered Nov 05 '22 03:11

Tim Cooper