pointers - 取消引用结构指针是否复制结构?

标签 pointers go

我有this code :

type countHolder struct {
    count int
}

func main() {
    a := &countHolder{1}
    b := *a
    a.count = 2
    println(b.count)
}

我预计输出为 2,但输出为 1。

我的理解是:

  1. a := &countHolder{1}//a 是指向数据从地址 x 开始的结构的指针
  2. b := *a//b 现在等于地址 x
  3. a.count = 2//存储在地址 x 的结构体的计数值变为 2

我哪里错了? b := *a 是在创建结构的副本吗?

最佳答案

来自fine specification :

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)
}

快速查看ab 是什么类型(分别是*counterHoldercounterHolder ,在这种情况下)。

关于pointers - 取消引用结构指针是否复制结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312954/

相关文章:

c - 为什么我会出现段错误?

go - 不允许创建命名空间操作?

json - 如何在带有 json 键的 GO 中使用 switch?

多个文件错误 : dereferencing pointer to incomplete type 中的 c 结构

c - 如何在函数中使用数组指针?

c++ - 指针和对象切片

c++ - 删除指针的段错误

arrays - Goroutines 共享 slice : : trying to understand a data race

go - 如何将内部包与 go 模块一起使用?

intellij-idea - GO SDK的位置