Home > Backend Development > Golang > To Embed or Not to Embed: When Should You Use Pointers in Struct Embedding in Go?

To Embed or Not to Embed: When Should You Use Pointers in Struct Embedding in Go?

Patricia Arquette
Release: 2024-10-30 18:01:30
Original
435 people have browsed it

 To Embed or Not to Embed: When Should You Use Pointers in Struct Embedding in Go?

Embedding in Go: Pointer Versus Value

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:

  • Dynamic Initialization: One can leverage functions that use the NewX idiom to return a struct by pointer for initialization purposes.
  • Dynamic Flexibility: Embedding a pointer allows changing the embedded instance at runtime, enabling multiple Render instances to share a single Bitmap instance.
  • Flyweight Pattern: Embed by pointer supports the Flyweight Pattern, where many instances share an underlying data structure and exhibits significant memory savings.

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!

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