Pointer vs. Value Embedding in Go: When to Choose Which?

DDD
Release: 2024-11-20 02:32:02
Original
158 people have browsed it

Pointer vs. Value Embedding in Go: When to Choose Which?

Pointer vs. Value Embedding in Go

When embedding a struct into another in Golang, the choice arises between embedding by pointer or by value. While both methods offer functionality, the optimal approach depends on a few factors.

Embedding by Pointer

By embedding a struct by pointer, you essentially create a hidden pointer to the embedded struct within the parent struct. This allows the parent struct to access the methods and data of the embedded struct indirectly through the pointer.

Consider the following example:

type Bitmap struct {
    data [4][4]bool
}

type Renderer struct {
    *Bitmap
    on uint8
    off uint8
}
Copy after login

In this case, Renderer embeds *Bitmap, meaning that it now has an indirect reference to the Bitmap struct. This approach is useful when:

  • Renderer is passed around by value, but the methods you need on Bitmap are defined on *Bitmap.
  • Bitmap has a constructor function that returns a pointer, and the zero value of Bitmap is not usable.

Embedding by Value

Alternatively, you can embed a struct by value, which copies the data of the embedded struct directly into the parent struct. This method allows direct access to the data and methods of the embedded struct, without the need for a pointer.

Using the same example:

type Bitmap struct {
    data [4][4]bool
}

type Renderer struct {
    Bitmap // Embedding by value
    on uint8
    off uint8
}
Copy after login

Embedding by value is preferred when:

  • Renderer is passed around as a pointer.
  • All the Bitmap methods are value methods.
  • The embedded struct is small, making locality of access and memory allocation efficient.

Which is More Preferred?

The choice between embedding by pointer or by value depends on the specific use case. By considering factors such as the value passing behavior of the parent struct, the methods defined on the embedded struct, and the characteristics of the embedded struct itself, you can determine the most appropriate embedding strategy for your application.

The above is the detailed content of Pointer vs. Value Embedding in Go: When to Choose Which?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template