Embedding in Go: When to Use a Pointer
When embedding a struct within another struct, the decision between using a pointer or value depends on the desired functionality and memory management considerations.
Using a Value
Embedding a struct by value means that a copy of the embedded struct is stored within the containing struct. This is suitable for situations where:
<code class="go">type Job struct { Command string log.Logger }</code>
Using a Pointer
Embedding a struct by pointer allows for memory sharing between multiple instances of the containing struct. This is useful for:
<code class="go">type Job struct { Command string *log.Logger }</code>
Embed by Pointer Advantages
Eric Urban ("hydrogen18") coined the term "embed by pointer." It offers advantages such as:
Flyweight Pattern with Embed by Pointer
By embedding a pointer to a Bitmap struct, multiple Renderer structs can share the same underlying bitmap data, reducing memory consumption and enabling runtime flexibility.
<code class="go">type Bitmap struct{ data [4][5]bool } type Renderer struct{ *Bitmap //Embed by pointer on uint8 off uint8 }</code>
Limitations of Embed by Pointer
Anonymous fields cannot have a pointer to a pointer or pointer to an interface type because these types do not have methods. This restriction is intended to prevent incorrect uses of pointers to interfaces and maintain consistency in the language.
The above is the detailed content of Embedding in Go: When to Use a Pointer vs. a Value?. For more information, please follow other related articles on the PHP Chinese website!