Home > Backend Development > Golang > When Embedding Structs in Go: Pointers or Embedded Values?

When Embedding Structs in Go: Pointers or Embedded Values?

Linda Hamilton
Release: 2024-10-31 06:28:30
Original
287 people have browsed it

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>
Copy after login

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:

  • Initialization flexibility: Functions that use the NewX idiom typically return a struct by pointer, allowing easy initialization.
  • Dynamic extensibility: Embedding a pointer enables you to change the embedded instance dynamically at runtime without having to instantiate the struct. This can be useful for scenarios like the Flyweight Pattern.

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template