2016-06-21 1 views
5

안녕하세요, 저는 Go을 배우고 있습니다. 저는 약간의 반성을하고있었습니다. 나는 다음과 같은 경우에 붙어있어 :슬라이스 반사에 요소를 추가하려면 어떻게해야합니까?

  1. 내가 structslice 나는이 조각 여기

에 새로운 요소를 추가하려면 다음

  • 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.

  • +0

    가능한 중복 : 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

    답변

    0

    원하는대로 할 수 있습니까? (playground link)

    package main 
    
    import (
        "fmt" 
        "reflect" 
    ) 
    
    type A struct{ Name string } 
    
    func main() { 
        bbb(A{}) 
    } 
    
    func aaa(v interface{}) interface{} { 
        sl := reflect.Indirect(reflect.ValueOf(v)) 
        typeOfT := sl.Type().Elem() 
    
        ptr := reflect.New(typeOfT).Interface() 
        s := reflect.ValueOf(ptr).Elem() 
        return reflect.Append(sl, s) 
    } 
    
    func bbb(v interface{}) { 
        myType := reflect.TypeOf(v) 
        models := reflect.MakeSlice(reflect.SliceOf(myType), 0, 1).Interface() 
        fmt.Println(aaa(models)) 
    } 
    

    새 슬라이스를 반환합니다. 반환 값없이이 작업을 수행하려면 간접적 인 포인터 (포인터에 대한 포인터)가 필요하다고 생각합니다.하지만 Go에서 리플렉션을 처음 수행 한 것이므로 잘못 될 수 있습니다.

    +0

    하지만 요점은 내가 참조로 작업하고 싶은 새로운 객체를 반환하고 싶지 않다는 것입니다. 많은 패키지는 json 인 코드/디코드를 좋아합니다. 또는 SQL 스캔 등 – Vardius

    +0

    @ Vardius : 포인터로 시작하지 않으므로 새 포인터를 어딘가에 만들어야합니다. 포인터를 인터페이스에 전달한다고해서 값에 대한 포인터가 생기는 것은 아닙니다. – JimB

    +0

    @JimB 내 진행 상황을 내 질문으로 업데이트했습니다. – Vardius

    관련 문제