Home > Article > Backend Development > When Embedding Structs in Go: Pointers or Embedded Values?
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:
<code class="go">type Job struct { Command string *log.Logger }</code>
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
<code class="go">type Bitmap struct{ data [4][5]bool } type Renderer struct{ *Bitmap //Embed by pointer on uint8 off uint8 }</code>
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.
The above is the detailed content of When Embedding Structs in Go: Pointers or Embedded Values?. For more information, please follow other related articles on the PHP Chinese website!