将struct赋给循环内的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}]发布于 2021-10-15 10:14:34
原因是,通过在z上迭代,您正在制作z元素的副本,标识为x。换句话说,更新x并不意味着您要更新z,而是更新它的元素的副本。您应该按照以下步骤进行操作:
for i, _ := range z {
z[i].A = c
}我已经把它复制到playground上了。
https://stackoverflow.com/questions/69581769
复制相似问题