英文:
Assign struct to struct inside slice of struct
问题
在循环中将结构体赋值给另一个结构体时出现了奇怪的行为。
package main
import (
"fmt"
)
func main() {
type A struct {
a string
}
type B struct {
A
b string
}
var z []B
c := A{a:"Test"}
d := B{A:c, b:"Test"}
fmt.Println(c)
fmt.Println(d)
z = append(z, B{b:"Test"})
z = append(z, B{b:"Test"})
fmt.Println(z)
for _, x := range z {
x.A = c
}
fmt.Println(z)
}
输出结果:
{Test}
{{Test} Test}
[{{} Test} {{} Test}]
[{{} Test} {{} Test}]
期望的结果:
{Test}
{{Test} Test}
[{{} Test} {{} Test}]
[{{Test} Test} {{Test} Test}]
在Go Playground上检查。
英文:
Weird behavior when assign struct to struct inside loop.
package main
import (
"fmt"
)
func main() {
type A struct {
a string
}
type B struct {
A
b string
}
var z []B
c := A{a:"Test"}
d := B{A:c,b:"Test"}
fmt.Println(c)
fmt.Println(d)
z = append(z, B{b:"Test"})
z = append(z, B{b:"Test"})
fmt.Println(z)
for _, x := range z {
x.A = c
}
fmt.Println(z)
}
Output:
{Test}
{{Test} Test}
[{{} Test} {{} Test}]
[{{} Test} {{} Test}]
Expected Value:
{Test}
{{Test} Test}
[{{} Test} {{} Test}]
[{{Test} Test} {{Test} Test}]
Check on this Go Playground
答案1
得分: 1
原因是,通过对z
进行迭代,你正在复制z
的元素,并将其标识为x
。换句话说,更新x
并不意味着你正在更新z
,而是在更新其元素的副本。你应该按照以下方式进行操作:
for i, _ := range z {
z[i].A = c
}
我已经将相同的代码复制到playground中。
英文:
The reason is, by iterating on z
, you are making a copy of elements of z
, identified as x
. In other words, updating x
doesn't mean you're updating z
but a copy of it's elements. You should do it as follows:
for i, _ := range z {
z[i].A = c
}
I've copied the same to playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论