douji9518 2018-03-16 03:55
浏览 24
已采纳

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

I have this code:

type countHolder struct {
    count int
}

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

I expected the output to be 2, but the output was 1.

My understanding was that:

  1. a := &countHolder{1} // a is pointer to struct with data starting at address x
  2. b := *a // b now equals address x
  3. a.count = 2 // the struct stored at address x has its count value changed to 2

Where am I wrong? is b := *a creating a copy of the struct?

  • 写回答

1条回答 默认 最新

  • doujiu8145 2018-03-16 05:25
    关注

    From the 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. [...]

    That means that the unary & operator gives you the address of something so a in:

    a := &countHolder{1}
    

    is a pointer. The unary * operator in:

    b := *a
    

    dereferences the pointer a and leaves you with a countHolder struct on the right side so b is a copy of the struct that a points to. Since b is a copy of the struct, modifying a.count:

    a.count = 2
    

    (which could also be written as (*a).count = 2) won't have any affect on b.

    You could also have a look at (https://play.golang.org/p/Zubs8qYBA_K):

    func main() {
        a := &countHolder{1}
        b := *a
        fmt.Printf("%T
    %T
    ", a, b)
    }
    

    to have a quick look at what types a and b are (*counterHolder and counterHolder, respectively, in this case).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序