Hi i am learning Go
and i was doing some reflection. I got stuck in a case like this:
- I want to create a
slice
ofstruct
passed to function asinterface{}
- Then I want to append new elements to this slice
Here is a playground with the code example.
package main
import (
"fmt"
"reflect"
)
type A struct{ Name string }
func main() {
bbb(A{})
}
func aaa(v interface{}) {
sl := reflect.ValueOf(v).Elem()
typeOfT := sl.Type()
ptr := reflect.New(typeOfT).Interface()
s := reflect.ValueOf(ptr).Elem()
sl.Set(reflect.Append(sl, s))
ptr = reflect.New(typeOfT).Interface()
s = reflect.ValueOf(ptr).Elem()
sl.Set(reflect.Append(sl, s))
}
func bbb(v interface{}) {
myType := reflect.TypeOf(v)
models := reflect.Zero(reflect.SliceOf(myType)).Interface()
aaa(&models)
fmt.Println(models)
}
Error: panic: reflect: call of reflect.Append on interface Value
Is there a way to make it work ? Note: that i want to work on a reference.
Solution:
Here is what i manage to do: playground.