如何附加反射切片?

时间:2017-04-04 05:31:27

标签: go

我正在尝试这样做:

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)
}

但我收到错误:

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

我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

使用&s获取结构的可寻址Value

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