Home  >  Article  >  Backend Development  >  Embedded Struct vs Pointer to Struct: What\'s the Deal with Zero Values and Copying?

Embedded Struct vs Pointer to Struct: What\'s the Deal with Zero Values and Copying?

DDD
DDDOriginal
2024-10-30 09:12:03237browse

Embedded Struct vs Pointer to Struct: What's the Deal with Zero Values and Copying?

Embedded Struct vs Pointer to Struct: Impacts on Zero Values and Copying

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:

<code class="go">type AObj struct { B }
var aObj AObj
aObj.Print() // Prints 0 (B's zero value)</code>

In contrast, embedding *B results in a zero value with a nil pointer, preventing direct use:

<code class="go">type APtr struct { *B }
var aPtr APtr
aPtr.Print() // Panics (nil pointer dereference)</code>

Copying

Object copying behavior depends on the embedding type. When B is embedded as an object, a new object is created upon copying:

<code class="go">type AObj struct { B }
aObj2 := aObj
aObj.X = 1
aObj2.Print() // Prints 0 (copy of B's zero value)</code>

Conversely, with pointer embedding (*B), both original and copied objects share the same underlying B object, allowing for synchronized changes:

<code class="go">type APtr struct { *B }
aPtr.B = &B{}
aPtr2 := aPtr
aPtr.X = 1
aPtr2.Print() // Prints 1 (shared underlying B)</code>

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.

The above is the detailed content of Embedded Struct vs Pointer to Struct: What\'s the Deal with Zero Values and Copying?. 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