我有this code :
type countHolder struct {
count int
}
func main() {
a := &countHolder{1}
b := *a
a.count = 2
println(b.count)
}
我预计输出为 2,但输出为 1。
我的理解是:
a := &countHolder{1}
//a 是指向数据从地址 x 开始的结构的指针b := *a
//b 现在等于地址 xa.count = 2
//存储在地址 x 的结构体的计数值变为 2
我哪里错了? b := *a
是在创建结构的副本吗?
最佳答案
For an operand x of type T, the address operation &x generates a pointer of type *T to x. [...]
For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x. [...]
这意味着一元 &
运算符为您提供了某物的地址,因此 a
在:
a := &countHolder{1}
是一个指针。一元 *
运算符在:
b := *a
取消引用指针 a
并在右侧留下一个 countHolder
结构,因此 b
是 结构的副本>a
指向。由于 b
是结构的副本,因此修改 a.count
:
a.count = 2
(也可以写成(*a).count = 2
)不会对b
产生任何影响。
你也可以看看 ( https://play.golang.org/p/Zubs8qYBA_K ):
func main() {
a := &countHolder{1}
b := *a
fmt.Printf("%T\n%T\n", a, b)
}
快速查看a
和b
是什么类型(分别是*counterHolder
和counterHolder
,在这种情况下)。
关于pointers - 取消引用结构指针是否复制结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312954/