Does dereferencing a structure return a new copy of the structure?

Why, when we refer to struct using (*structObj) , Go seems to return a new copy of structObj , rather than returning the same address of the original structObj ? This may be my misunderstanding, so I ask for clarification.

 package main import ( "fmt" ) type me struct { color string total int } func study() *me { p := me{} p.color = "tomato" fmt.Printf("%p\n", &p.color) return &p } func main() { p := study() fmt.Printf("&p.color = %p\n", &p.color) obj := *p fmt.Printf("&obj.color = %p\n", &obj.color) fmt.Printf("obj = %+v\n", obj) p.color = "purple" fmt.Printf("p.color = %p\n", &p.color) fmt.Printf("p = %+v\n", p) fmt.Printf("obj = %+v\n", obj) obj2 := *p fmt.Printf("obj2 = %+v\n", obj2) } 

Exit

 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 to the site

+10
pointers struct dereference go
source share
3 answers

When you write

 obj := *p 

You copy the value of the structure pointed to by p ( * dereferences p ). It looks like:

 var obj me = *p 

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

Note that obj is of type me , and p is of type *me . But these are separate values. Changing the value of the obj field will not affect the value of this field in p (unless the me structure has a reference type as a field, that is, a slice, map, or channel. See here and here .). If you want to achieve this effect, use:

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

Now obj points to the same object as p . They still have different addresses, but they contain the same address of the actual object me .

+9
source share

No, โ€œassignmentโ€ always creates a copy in Go, including assignment of function and method arguments. The obj := *p operator obj := *p copies the value of *p to obj .

If you change the operator p.color = "purple" to (*p).color = "purple" , you will get the same result, because dereferencing p itself does not create a copy.

+13
source share

tl; dr Dereferencing (using the * operator) in Go does not make a copy. Returns the value that the pointer points to.

+4
source share

All Articles