Home  >  Article  >  Backend Development  >  Embedding in Go: When to Use a Pointer vs. a Value?

Embedding in Go: When to Use a Pointer vs. a Value?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 08:21:29124browse

Embedding in Go: When to Use a Pointer vs. a Value?

Embedding in Go: When to Use a Pointer

When embedding a struct within another struct, the decision between using a pointer or value depends on the desired functionality and memory management considerations.

Using a Value

Embedding a struct by value means that a copy of the embedded struct is stored within the containing struct. This is suitable for situations where:

  • The embedded struct is small and frequently accessed.
  • There is no need to dynamically change the embedded struct at runtime.
<code class="go">type Job struct {
    Command string
    log.Logger
}</code>

Using a Pointer

Embedding a struct by pointer allows for memory sharing between multiple instances of the containing struct. This is useful for:

  • Embedding large or complex structs to avoid unnecessary duplication.
  • Enabling dynamic changes to the embedded struct at runtime.
<code class="go">type Job struct {
    Command string
    *log.Logger
}</code>

Embed by Pointer Advantages

Eric Urban ("hydrogen18") coined the term "embed by pointer." It offers advantages such as:

  • Using functions that initialize structs by reference, leveraging the NewX idiom.
  • Embedding functionality of a type without needing to know its instantiation time.

Flyweight Pattern with Embed by Pointer

By embedding a pointer to a Bitmap struct, multiple Renderer structs can share the same underlying bitmap data, reducing memory consumption and enabling runtime flexibility.

<code class="go">type Bitmap struct{
    data [4][5]bool
}

type Renderer struct{
    *Bitmap //Embed by pointer
    on uint8
    off uint8
}</code>

Limitations of Embed by Pointer

Anonymous fields cannot have a pointer to a pointer or pointer to an interface type because these types do not have methods. This restriction is intended to prevent incorrect uses of pointers to interfaces and maintain consistency in the language.

The above is the detailed content of Embedding in Go: When to Use a Pointer vs. a Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn