Dereferencing Structs in Go: Creation of New Copies
When working with structs in Go, it's important to understand the behavior of dereferencing. Dereferencing an object essentially returns a copy of the value it points to. This can be counterintuitive for some programmers coming from other languages, where dereferencing typically returns the object itself.
Consider the following Go 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) 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) }
In this example, the study() function creates a new me struct and returns a pointer to it. We then assign this pointer to a variable p. When we dereference p and assign it to obj, we create a new copy of the struct. This new copy has a different memory address from the original struct pointed to by p.
This means that changing the fields of obj will not affect the fields of the original struct, and vice versa. To create a reference to the original struct, we would need to assign the pointer from p to obj:
obj := p
In this case, obj and p would point to the same struct and any changes made to one would be reflected in the other.
The above is the detailed content of Does Dereferencing a Go Struct Create a Copy or a Reference?. For more information, please follow other related articles on the PHP Chinese website!