Home >Backend Development >Golang >Does Dereferencing a Go Struct Create a New Copy?
Does Dereferencing a Struct Create a New Copy in Go?
In Go, when a variable of a struct type is passed by reference using the asterisk (*) operator, a misconception may arise that the dereferenced variable represents the same address as the original struct.
However, as demonstrated in the given code snippet:
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) // Address of p.color return &p } func main() { p := study() // p is a pointer to a struct fmt.Printf("&p.color = %p\n", &p.color) // Address of p.color obj := *p // obj is a copy of the struct pointed to by p fmt.Printf("&obj.color = %p\n", &obj.color) // Address of obj.color fmt.Printf("obj = %+v\n", obj) p.color = "purple" // Changes color of the struct pointed by p fmt.Printf("p.color = %p\n", &p.color) fmt.Printf("p = %+v\n", p) fmt.Printf("obj = %+v\n", obj) obj2 := *p // Another copy is made fmt.Printf("obj2 = %+v\n", obj2) }
When we execute this code, the output shows that the dereferenced variable obj has a different address than the original struct p. This is because:
Dereferencing creates a new copy:
The line obj := *p creates a new variable obj of the same type as p (me), and initializes it with a copy of the value pointed by p. This means that any changes made to obj will not affect the original struct.
Effectively assigning a new struct value to another:
Similar to var obj me = *p, the dereference operation in obj := *p assigns a new struct value to the variable obj. This creates a new copy with separate memory.
Using the asterisk operator with caution:
While the asterisk operator provides pointer semantics, it's important to understand its effects on variables. When a value is assigned with the * (dereference) operator, it creates a new copy, not a new reference to the original variable.
The above is the detailed content of Does Dereferencing a Go Struct Create a New Copy?. For more information, please follow other related articles on the PHP Chinese website!