1- Using reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)
and
reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
,
Like this working sample code:
package main
import "fmt"
import "reflect"
func main() {
elemType := reflect.TypeOf(TestStruct{})
elemSlice := reflect.MakeSlice(reflect.SliceOf(elemType), 0, 10)
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
fmt.Println(elemSlice) // [{Testing}]
}
type TestStruct struct {
TestStr string
}
2- Using reflect.New(reflect.SliceOf(elemType)).Elem()
and
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
Like this working sample code:
package main
import "fmt"
import "reflect"
type TestStruct struct {
TestStr string
}
func main() {
elemType := reflect.TypeOf(TestStruct{})
elemSlice := reflect.New(reflect.SliceOf(elemType)).Elem()
elemSlice = reflect.Append(elemSlice, reflect.ValueOf(TestStruct{"Testing"}))
fmt.Printf("%+v\n", elemSlice) // [{TestStr:Testing}]
fmt.Println(elemSlice) // [{Testing}]
}
Output:
[{TestStr:Testing}]
[{Testing}]
3- If you need append
, the only way is using s := elemSlice.([]TestStruct)
, like this working sample code:
package main
import "fmt"
import "reflect"
type TestStruct struct {
TestStr string
}
func main() {
elemType := reflect.TypeOf(TestStruct{})
elemSlice := reflect.New(reflect.SliceOf(elemType)).Elem().Interface()
s := elemSlice.([]TestStruct)
s = append(s, TestStruct{"Testing"})
fmt.Printf("%+v\n", elemSlice) // []
fmt.Println(s) // [{Testing}]
}