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

Mary-Kate Olsen
Release: 2024-11-01 02:51:27
Original
641 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!