如何使用反射在切片中追加元素?

huangapple go评论105阅读模式
英文:

How do I append to a slice with reflect?

问题

我正在尝试做这个:

  1. type S struct {
  2. Name string
  3. Children []interface{}
  4. }
  5. func main() {
  6. s := S{Name: "Bob", Children: []interface{}{}}
  7. fmt.Println("%v", s)
  8. s.Children = append(s.Children, "Tom")
  9. fmt.Println("%v", s)
  10. // 如何使用反射完成上面的行为来添加"Jane"?
  11. c := reflect.ValueOf(&s).Elem().FieldByName("Children")
  12. newSlice := reflect.Append(c, reflect.ValueOf("Jane"))
  13. reflect.ValueOf(&s).Elem().FieldByName("Children").Set(newSlice)
  14. fmt.Println("%v", s)
  15. }

但是我遇到了错误:

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

我做错了什么?

英文:

I am trying to do this:

  1. type S struct {
  2. Name string
  3. Children []interface{}
  4. }
  5. func main() {
  6. s := S{Name: "Bob", Children: []interface{}{}}
  7. fmt.Println("%v", s)
  8. s.Children = append(s.Children, "Tom")
  9. fmt.Println("%v", s)
  10. // How do I do the above line with reflect? To add "Jane"?
  11. c := reflect.ValueOf(s).FieldByName("Children")
  12. newSlice := reflect.Append(c, reflect.ValueOf("Jane"))
  13. reflect.ValueOf(s).FieldByName("Children").Set(newSlice)
  14. fmt.Println("%v", s)
  15. }

But I am getting the error:

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

What am I doing wrong?

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

答案1

得分: 3

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

  1. c := reflect.ValueOf(s).FieldByName("Children")
  2. newSlice := reflect.Append(c, reflect.ValueOf("Jane"))
  3. reflect.ValueOf(&s).Elem().FieldByName("Children").Set(newSlice)
  4. fmt.Printf("%v", s)
  5. //输出:
  6. //{Bob [Tom Jane]}

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

英文:

Use &s to obtain addressable Value of your struct :

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

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

huangapple
  • 本文由 发表于 2017年4月4日 13:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/43198959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定