mercredi 25 octobre 2017

Appending to a slice using reflection

I would like to append to a slice using only reflection. But I can't figure out how to "replace" the value of a with the new slice.

func main() {
    fmt.Println("Hello, playground")

    a := []string {"a","b","c"}

    values := []string {"d","e"}

    v := reflect.ValueOf(a)

    fmt.Printf("%t\n\n", v.Type())
    fmt.Printf("%t\n\n", v.Type().Elem().Kind())

    for _, val := range values {
        v.Set(reflect.Append(v, reflect.ValueOf(val)))
    }

    fmt.Printf("%t - %v", a, a)
}

This code is available for fiddling at http://ift.tt/2z6fMDC.





Aucun commentaire:

Enregistrer un commentaire