Go Dereferencing: Copies or Not, That Is the Question
When accessing a Go struct using the dereference operator (*), users may wonder if the result is a new copy of the struct or a reference to the original object.
Understanding the Behavior
In the provided code snippet:
type me struct { color string total int } func study() *me { p := me{} return &p } obj := *study()
study() returns a pointer to a me struct. Dereferencing it in obj creates a copy of the struct. This is evident from the memory addresses of &p.color and &obj.color, which are different.
One might expect the dereferenced struct obj to have the same memory address as the original struct, but that's not the case in this instance. This behavior can be attributed to Go's automatic deallocation of variables at the end of their scope.
When It's Actually a Reference
To achieve reference behavior, one can assign a pointer directly to the struct using:
obj := study()
In this case, obj will be a pointer to the original me struct, and changes to either p or obj will affect the same underlying struct.
Conclusion
When dereferencing a struct in Go, it's important to understand that the result is a copy of the original struct unless a pointer to the struct is explicitly assigned. This behavior ensures that changes made to the dereferenced struct do not affect the original struct, maintaining encapsulation and variable independence.
The above is the detailed content of Does Go\'s Dereference Operator Create a Copy or a Reference to the Original Struct?. For more information, please follow other related articles on the PHP Chinese website!