Embedding Structs in Go: When to Use a Pointer
When considering embedding one struct within another, the decision of whether to use a pointer or a value for the embedded field arises. This article explores the nuances of this implementation choice and provides examples to illustrate the potential benefits and implications.
Embedding by Pointer
The Go spec allows for embedding structs as pointers or values. For non-interface types, specifying an anonymous field as a type name T or a pointer to a non-interface type name *T is permissible.
Advantages of Embedding by Pointer:
Embedding by Value
Embedding the struct as a value embeds all its functionality without the need for instantiation knowledge. It effectively promotes the embedded struct's methods to the enclosing struct.
Consider the Following Examples:
<code class="go">type Job struct { Command string *log.Logger }</code>
In this example, the Job struct embeds a pointer to the log.Logger type. This approach enables the Job struct to access Logger methods while allowing for dynamic assignment of different Logger instances.
<code class="go">type Job struct { Command string log.Logger }</code>
Here, the Job struct directly embeds the log.Logger type as a value. The promoted Logger methods can now be accessed directly from the Job struct.
Conclusion
Both embedding by pointer and by value have their unique advantages and considerations. The choice between the two approaches depends on whether or not dynamic assignment or the promotion of methods is desired. Understanding the implications of each method can help in making informed decisions when embedding structs in Go.
The above is the detailed content of Embedding Structs in Go: Pointer or Value? When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!