안녕하세요, 저는 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-go/37713982 – JimB