When using a struct type as a pointer (i.e., with pointer receivers, constructors returning A, etc.), the choice between embedding the struct (as B) or its pointer (as B) has subtle yet important consequences.
Zero Values
The zero values of the two options differ significantly. Embeddings B directly creates an embedded object with its zero value, which allows for immediate operations on it:
type AObj struct { B }
var aObj AObj
aObj.Print() // Prints 0 (B's zero value)
In contrast, embedding *B results in a zero value with a nil pointer, preventing direct use:
type APtr struct { *B }
var aPtr APtr
aPtr.Print() // Panics (nil pointer dereference)
Copying
Object copying behavior depends on the embedding type. When B is embedded as an object, a new object is created upon copying:
type AObj struct { B }
aObj2 := aObj
aObj.X = 1
aObj2.Print() // Prints 0 (copy of B's zero value)
Conversely, with pointer embedding (*B), both original and copied objects share the same underlying B object, allowing for synchronized changes:
type APtr struct { *B }
aPtr.B = &B{}
aPtr2 := aPtr
aPtr.X = 1
aPtr2.Print() // Prints 1 (shared underlying B)
These differences have practical implications for code readability, maintainability, and performance optimization. By understanding the subtle nuances of struct embedding vs pointer embedding, developers can proactively avoid potential pitfalls and leverage the most appropriate approach for their specific use cases.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3