Home > Backend Development > Golang > 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
Release: 2024-10-30 09:12:03
Original
355 people have browsed it

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template