对于以下代码,我期望输出 {"NewName" [{"NewName" []}]}
但它没有更新子结构。我们如何确保它更新层次结构中的每个结构。
package main
import (
"fmt"
)
type red struct {
Name string
Child []red
}
func (r *red) setName(nameString string){
r.Name = nameString
for _, child := range r.Child{
child.setName(nameString)
}
}
func main() {
obj := red{Name:"NameA",Child:[]red{red{Name: "NameB"}}}
fmt.Print(obj)
fmt.Print("\n")
obj.setName("NewName")
//Expectation {"NewName" [{"NewName" []}]}
fmt.Print(obj)
}
最佳答案
您不需要像其他人的答案所建议的那样到处使用指针。您的代码中的问题是当您迭代子项时,您会获得每个副本的值,在此副本上设置名称,但不要将该副本保存到 slice 中。
package main
import (
"fmt"
)
type red struct {
Name string
Child []red
}
func (r *red) setName(s string) {
r.Name = s
for i, ch := range r.Child {
ch.setName(s) // ch is not a ptr to r.Child[i], it is a value copy
r.Child[i] = ch // so you must re assign the copy into the slice!
}
}
func main() {
obj := red{Name: "A", Child: []red{red{Name: "B"}}}
fmt.Print(obj)
fmt.Print("\n")
obj.setName("X")
//Expectation {X [{X []}]}
fmt.Print(obj)
}
关于go - 如何以递归方式更新结构 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62164402/