嗨,我正在學習Go
,我正在做一些反思。我被困在一個情況是這樣的:如何添加切片反射元素?
- 我想創建的
struct
一個slice
傳遞給函數作爲interface{}
- 然後我想新的元素添加到這片
這裏是一個playground與代碼示例。
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)
}
錯誤:panic: reflect: call of reflect.Append on interface Value
有沒有一種方法,使工作? 注意:我想參考一下。
解決方案:
這是我能做到:playground。
可能的重複:http://stackoverflow.com/questions/34600817/pointer-to-interface-with-saving-type/34600906和http://stackoverflow.com/questions/37713749/unmarshal -into-array-of-structs-determined-at-runtime-in-go/37713982 – JimB