Home > Backend Development > Golang > When Should You Use Pointer vs. Value Embedding in Go?

When Should You Use Pointer vs. Value Embedding in Go?

Barbara Streisand
Release: 2024-11-15 02:28:02
Original
302 people have browsed it

When Should You Use Pointer vs. Value Embedding in Go?

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

Value vs. Pointer

The preferred choice between pointer and value embedding depends on several factors:

  • Usage of Renderer: If Renderer is passed by value and its methods are defined on *Bitmap, embedding by pointer is necessary.
  • Renderer Type: If Renderer is passed by pointer, embedding by value is possible while still allowing access to pointer methods.
  • Bitmap Constructor: If Bitmap's constructor returns a pointer and its zero value is not usable, embedding by pointer is preferable to prevent unnecessary copying.
  • Method Implementation: If all Bitmap methods are value methods, embedding by value is the best option.

Specific Case

In the example provided:

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

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

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!

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