Why does the memory address of a reference change?

Hi,

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 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:

[restful] 2017/01/18 09:30:18 log.go:30: Whatever.GetNameByReference() memory address: 0xc420034020
[restful] 2017/01/18 09:30:18 log.go:30: Whatever.GetNameByReference() memory address: 0xc420034030
[restful] 2017/01/18 09:30:18 log.go:30: Whatever.GetNameByReference() memory address: 0xc420034038
```

It does not. Your program is wrong. You have a pointer receiver and you are asking for an address of this receiver. Instead, use “%p” to print pointer value.

package main

import "log"

type Whatever struct{
	Name string
}

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

	return whatever.Name
}

func evaluateMemoryAddressWhenNotWritingAnything()  {
	whatever := Whatever{}

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

func main() {
	evaluateMemoryAddressWhenNotWritingAnything()
}
1 Like

Hey grzegorz.zur,

lesson learned! Thanks a lot! :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.