dimanche 28 août 2016

How to reflect.New a slice and reflect.AppendSlice it to a source slice

I want to reflect.New an []interface like []int and append it into another slice.

My code must have an error, but I don't know how to make it right and how to understand deeply the reflect.New and reflect.AppendSlice usage.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var a []int
    var value reflect.Value = reflect.ValueOf(&a)


    if !value.CanSet() {
        fmt.Println("go here", value.CanSet())
        value = value.Elem() 
        fmt.Println("go here", value.CanSet())  
    }
    fmt.Println("go here", value.Type())    
    s := reflect.New(value.Type())
    fmt.Println("go here", s.Elem())
    value = reflect.AppendSlice(value, reflect.ValueOf(s.Elem()))
    value = reflect.AppendSlice(value, reflect.ValueOf([]int{1, 2}))                
    value = reflect.AppendSlice(value, reflect.ValueOf([]int{3, 4, 5, 6, 7, 8, 9})) 

    fmt.Println(value.Kind(), value.Slice(0, value.Len()).Interface())
    //>>slice [1 2 3 4 5 6 7 8 9]
}

But it gives an error:

panic: reflect: call of reflect.AppendSlice on struct Value

goroutine 1 [running]:
panic(0x100a60, 0x1040e1a0)
    /usr/local/go/src/runtime/panic.go:500 +0x720
reflect.flag.mustBe(0x99, 0x17)
    /usr/local/go/src/reflect/value.go:201 +0xe0
reflect.AppendSlice(0xfa7e0, 0x1040e130, 0x197, 0x1116a0, 0x1040e190, 0x99, 0x0, 0x0, 0x0, 0x2)
    /usr/local/go/src/reflect/value.go:1825 +0x60
main.main()
    /tmp/sandbox476529744/main.go:21 +0x800

golang playground





Aucun commentaire:

Enregistrer un commentaire