2

I am trying to do this:

type S struct {
    Name string
    Children []interface{}
}

func main() {
    s := S{Name: "Bob", Children: []interface{}{}}
    fmt.Println("%v", s)

    s.Children = append(s.Children, "Tom")
    fmt.Println("%v", s)

    // How do I do the above line with reflect? To add "Jane"?
    c := reflect.ValueOf(s).FieldByName("Children")
    newSlice := reflect.Append(c, reflect.ValueOf("Jane"))
    reflect.ValueOf(s).FieldByName("Children").Set(newSlice)
    fmt.Println("%v", s)
}

But I am getting the error:

panic: reflect: reflect.Value.Set using unaddressable value

What am I doing wrong?

https://play.golang.org/p/Fwy_AAF-Ls

Elliot Chance
  • 5,526
  • 10
  • 49
  • 80
  • Related/possible duplicate : [in golang, using reflect, how do you set the value of a struct field?](http://stackoverflow.com/questions/6395076/in-golang-using-reflect-how-do-you-set-the-value-of-a-struct-field) – har07 Apr 04 '17 at 06:25

1 Answers1

3

Use &s to obtain addressable Value of your struct :

c := reflect.ValueOf(s).FieldByName("Children")
newSlice := reflect.Append(c, reflect.ValueOf("Jane"))
reflect.ValueOf(&s).Elem().FieldByName("Children").Set(newSlice)
fmt.Printf("%v", s)
//output:
//{Bob [Tom Jane]}

https://play.golang.org/p/y3t7mC4Lqi

har07
  • 88,338
  • 12
  • 84
  • 137