2017-04-04 112 views
1

我试图做到这一点:如何附加反映的切片?

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

+0

产品/可能重复:在golang,使用反映,你怎么设置的值struct field?](http://stackoverflow.com/questions/6395076/in-golang-using-reflect-how-do-you-set-the-value-of-a-struct-field) – har07

回答

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