为什么将值放入变量会创建一个副本,但取消引用却不会?
是编译器的简单优化,知道它可以只使用原始结构的地址,而创建变量总是分配新内存吗?
示例 1:
x1 := &struct{ x int }{x: 0}
y1 := *x1
z1 := &y1
z1.x++
fmt.Printf("--- 1:\n%#v\n%#v\n", x1, z1)
示例 2:
x2 := &struct{ x int }{x: 0}
z2 := &*x2
z2.x++
fmt.Printf("--- 2:\n%#v\n%#v\n", x2, z2)
在这里运行:https://play.golang.org/p/myugNmjrQFj
go 文档中是否有描述此行为的部分?
最佳答案
Is there a a part of the go documentation that describes this behavior?
是的,语言规范。参见 https://golang.org/ref/spec
关于pointers - 创建变量会创建一个副本,取消引用不会。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367210/