Embedding Structures: When to Prefer Pointers
When embedding one struct within another, there are two options: using a pointer or an embedded value. To guide this decision, it is important to understand the specifications and consider the advantages of each approach.
Pointers vs. Embedded Values
According to the Go specification, an anonymous field (also known as an embedded field) can be declared as a type name or as a pointer to a non-interface type name. This means you have the choice of using the type log.Logger or a pointer *log.Logger for the Logger field in the following example:
type Job struct {
Command string
*log.Logger
}
Benefits of Pointers
The article "Embedding in Go" by Eric Urban highlights the advantages of embedding a pointer, which is referred to as "embed by-pointer." These include:
Example of Pointer Embedding
type Bitmap struct{
data [4][5]bool
}
type Renderer struct{
*Bitmap //Embed by pointer
on uint8
off uint8
}
In this example, the Renderer type embeds a Bitmap by pointer. This means multiple instances of Renderer can share a single instance of Bitmap and customize their behavior independently.
Technical Limitations
It's important to note that you cannot use pointers to pointers or pointers to interfaces as anonymous fields. This restriction stems from the fact that these types do not have methods, which is a key aspect of embedding. Methods are promoted from the embedded type to the embedding type, allowing you to access them directly.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3