dongyun7571 2017-01-18 08:41
浏览 47
已采纳

为什么结构引用的内存地址会更改?

I have a struct and a method that's working on the structs reference. The pointer address is changing every time I call the method. Why is it like that?

Code

package main

import "k8s.io/contrib/compare/Godeps/_workspace/src/github.com/emicklei/go-restful/log"

type Whatever struct{
    Name string
}

func (whatever *Whatever) GetNameByReference() (string) {
log.Printf("Whatever.GetNameByReference() memory address: %v", &whatever)

    return whatever.Name
}

func evaluateMemoryAddressWhenNotWritingAnything()  {
    whatever := Whatever{}

    whatever.GetNameByReference()
    whatever.GetNameByReference()
    whatever.GetNameByReference()
}

func main() {
    evaluateMemoryAddressWhenNotWritingAnything()
}

Output:

log.go:30: Whatever.GetNameByReference() memory address: 0xc420034020
log.go:30: Whatever.GetNameByReference() memory address: 0xc420034030
log.go:30: Whatever.GetNameByReference() memory address: 0xc420034038
  • 写回答

3条回答 默认 最新

  • douhe8981 2017-01-18 08:55
    关注

    Never think and never talk about references. Go has no notion of "reference", everything is a value. Some things are pointer values. Your problem stems from thinking about *X as "a reference to an X" which it isn't: It is a value holding the memory address of an X (or nil).

    So in func (whatever *Whatever) the variable whatever is a pointer to a Whatever. The value of whatever is the memory address of the Whatever the pointer points to. You would like to print this memory address, i.e. the value of whatever.

    You do Printf("%v", &whatever). Remember: whatever is a variable (holding a memory address). So &whatever is the address of the variable itself: &whatever is of type **Whatever. What you find at the address &whatever is not the value you are interested in; it is just the temporary variable used to store the address of the original Whatever. Of course this temporary variable is not pinned in memory an may change freely.

    You should do Printf("%p", whatever). The verb %p is for pointer values and whateveris a pointer and you are interested in its value, so print this value.

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog