英文:
How do I append to a slice with reflect?
问题
我正在尝试做这个:
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)
// 如何使用反射完成上面的行为来添加"Jane"?
c := reflect.ValueOf(&s).Elem().FieldByName("Children")
newSlice := reflect.Append(c, reflect.ValueOf("Jane"))
reflect.ValueOf(&s).Elem().FieldByName("Children").Set(newSlice)
fmt.Println("%v", s)
}
但是我遇到了错误:
panic: reflect: reflect.Value.Set using unaddressable value
我做错了什么?
英文:
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?
答案1
得分: 3
使用&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)
//输出:
//{Bob [Tom Jane]}
链接:https://play.golang.org/p/y3t7mC4Lqi
英文:
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]}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论