0

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 https://play.golang.org/p/cDlyH3jBDS.

icza
  • 389,944
  • 63
  • 907
  • 827
cimnine
  • 3,987
  • 4
  • 33
  • 49

1 Answers1

3

You can't modify the value wrapped in reflect.Value if it originates from a non-pointer. If it would be allowed, you could only modify a copy and would cause more confusion. A slice value is a header containing a pointer to a backing array, a length and a capacity. When you pass a to reflect.ValueOf(), a copy of this header is made and passed, and any modification you could do on it could only modify this header-copy. Adding elements (and thus changing its length and potentially the pointer and capacity) would not be observed by the original slice header, the original would still point to the same array, and would still contain the same length and capacity values. For details see Are Golang function parameter passed as copy-on-write?; and Golang passing arrays to the function and modifying it.

You have to start from a pointer, and you may use Value.Elem() to obtain the reflect.Value descriptor of the pointed, dereferenced value. But you must start from a pointer.

Changing this single line in your code makes it work:

v := reflect.ValueOf(&a).Elem()

And also to print the type of a value, use the %T verb (%t is for bool values):

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

// ...

fmt.Printf("%T - %v", a, a)

Output (try it on the Go Playground):

Hello, playground
*reflect.rtype

reflect.Kind

[]string - [a b c d e]

For a deeper understanding of Go's reflection, read the blog post: The Laws of Reflection

And read related questions+answers:

Assigning a value to struct member through reflection in Go

Changing pointer type and value under interface with reflection

Using reflection SetString

icza
  • 389,944
  • 63
  • 907
  • 827
  • Would it be correct to say that, because I didn't pass a reference into `reflect.ValueOf`, every operation I performed using `reflect.*` was applied to a copy and therefore there was no way to modify the original `a`? – cimnine Oct 25 '17 at 11:29