doumengyin0491 2016-07-18 18:10
浏览 65
已采纳

取消引用结构是否会返回新的结构副本?

Why when we reference struct using (*structObj) does Go seem to return a new copy of structObj rather than return the same address of original structObj? This might be some misunderstanding of mine, so I seek clarification

package main

import (
    "fmt"
)

type me struct {
    color string
    total int
}

func study() *me {
    p := me{}
    p.color = "tomato"
    fmt.Printf("%p
", &p.color)
    return &p
}

func main() {
    p := study()
    fmt.Printf("&p.color = %p
", &p.color)

    obj := *p
    fmt.Printf("&obj.color = %p
", &obj.color)
    fmt.Printf("obj = %+v
", obj)

    p.color = "purple"
    fmt.Printf("p.color = %p
", &p.color)
    fmt.Printf("p = %+v
", p)
    fmt.Printf("obj  = %+v
", obj)

    obj2 := *p
    fmt.Printf("obj2 = %+v
", obj2)
}

Output

0x10434120
&p.color = 0x10434120
&obj.color = 0x10434140   //different than &p.color!
obj = {color:tomato total:0}
p.color = 0x10434120
p = &{color:purple total:0}
obj  = {color:tomato total:0}
obj2 = {color:purple total:0} // we get purple now when dereference again

Go playground

  • 写回答

3条回答 默认 最新

  • douzhuanqian8244 2016-07-18 18:15
    关注

    When you write

    obj := *p
    

    You are copying the value of struct pointed to by p (* dereferences p). It is similar to:

    var obj me = *p
    

    So obj is a new variable of type me, being initialized to the value of *p. This causes obj to have a different memory address.

    Note that obj if of type me, while p is of type *me. But they are separate values. Changing a value of a field of obj will not affect the value of that field in p (unless the me struct has a reference type in it as a field, i.e. slice, map or channels. See here and here.). If you want to bring about that effect, use:

    obj := p
    // equivalent to: var obj *me = p
    

    Now obj points to the same object as p. They still have different addresses themselves, but hold within them the same address of the actual me object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b