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

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

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?

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

答案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]}

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:

确定