我正在尝试这样做:
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
我做错了什么?
答案 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]}