Embedding Struct or Pointer to Struct as Pointer: Key Differences
When a struct type A acts as a pointer with only pointer receivers and constructors returning A,embedding another struct type B presents two options: embedding B directly or embedding B.
Zero Value Differences:
The zero values of A with embedded B versus embedded *B differ. When B is embedded directly, the zero value of A contains an embedded zero value of B, allowing safe usage without initialization:
<code class="go">type B struct { X int } func (b *B) Print() { fmt.Printf("%d\n", b.X) } type AObj struct { B } var aObj AObj aObj.Print() // prints 0</code>
However, embedding a nil pointer value in APtr's zero value makes direct usage impossible:
<code class="go">type APtr struct { *B } var aPtr APtr aPtr.Print() // panics</code>
Object Copying:
Objects are copied as expected. Creating a new AObj copies the embedded B:
<code class="go">aObj2 := aObj aObj.X = 1 aObj2.Print() // prints 0, due to the copy</code>
Conversely, creating a new APtr copies the *B, preserving the shared concrete object:
<code class="go">aPtr.B = &B{} aPtr2 := aPtr aPtr.X = 1 aPtr2.Print() // prints 1, due to shared reference</code>
Example:
https://play.golang.org/p/XmOgegwVFeE provides a runnable example demonstrating these differences.
The above is the detailed content of Embed a Struct or a Pointer to a Struct: When and Why?. For more information, please follow other related articles on the PHP Chinese website!