Home  >  Article  >  Backend Development  >  Embed a Struct or a Pointer to a Struct: When and Why?

Embed a Struct or a Pointer to a Struct: When and Why?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 02:51:27625browse

Embed a Struct or a Pointer to a Struct: When and Why?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn