Introduction
When embedding a struct within another struct in Go, one may wonder whether to use a pointer or a value. This article explores the differences and when each approach is appropriate.
Pointer Embedding
The spec allows for embedding either a type name T or a pointer to a non-interface type name *T, provided that T itself is not a pointer type.
Advantages of Embed by Pointer
As Eric Urban (hydrogen18) explains in "Embedding in Go," embed by pointer offers several advantages:
However, it's crucial to note that the embedded pointer will have methods promoted to the embedding type. Also, embedding a pointer to a pointer or interface is not permitted because these types do not have methods.
The above is the detailed content of To Embed or Not to Embed: When Should You Use Pointers in Struct Embedding in Go?. For more information, please follow other related articles on the PHP Chinese website!