Embedding in Go: Pointer vs. Value
Embedding is a feature in Go that allows a struct to inherit the fields and methods of another struct. This can be done either by pointer or by value.
Embedding by Pointer
type Bitmap struct { data [4][4]bool } type Renderer struct { *Bitmap // Pointer to Bitmap on uint8 off uint8 }
Value vs. Pointer
The preferred choice between pointer and value embedding depends on several factors:
Specific Case
In the example provided:
type Bitmap struct { data [4][4]bool } type Renderer struct { Bitmap // Embedded by value on uint8 off uint8 }
Embedding by value is likely the preferred option, given the small size of Bitmap. This approach provides locality of access and reduces memory allocations.
The above is the detailed content of When Should You Use Pointer vs. Value Embedding in Go?. For more information, please follow other related articles on the PHP Chinese website!