"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Embedding Structs in Go: Pointer or Value? When to Use Which?

Embedding Structs in Go: Pointer or Value? When to Use Which?

Published on 2024-11-17
Browse:207

Embedding Structs in Go: Pointer or Value? When to Use Which?

Embedding Structs in Go: When to Use a Pointer

When considering embedding one struct within another, the decision of whether to use a pointer or a value for the embedded field arises. This article explores the nuances of this implementation choice and provides examples to illustrate the potential benefits and implications.

Embedding by Pointer

The Go spec allows for embedding structs as pointers or values. For non-interface types, specifying an anonymous field as a type name T or a pointer to a non-interface type name *T is permissible.

Advantages of Embedding by Pointer:

  • This approach allows relying on functions that return structs by-pointer for initialization purposes.
  • Dynamically changing the instance being extended is possible. This feature is particularly useful in implementing the Flyweight Pattern, where multiple instances share the same underlying data structure.

Embedding by Value

Embedding the struct as a value embeds all its functionality without the need for instantiation knowledge. It effectively promotes the embedded struct's methods to the enclosing struct.

Consider the Following Examples:

type Job struct {
    Command string
    *log.Logger
}

In this example, the Job struct embeds a pointer to the log.Logger type. This approach enables the Job struct to access Logger methods while allowing for dynamic assignment of different Logger instances.

type Job struct {
    Command string
    log.Logger
}

Here, the Job struct directly embeds the log.Logger type as a value. The promoted Logger methods can now be accessed directly from the Job struct.

Conclusion

Both embedding by pointer and by value have their unique advantages and considerations. The choice between the two approaches depends on whether or not dynamic assignment or the promotion of methods is desired. Understanding the implications of each method can help in making informed decisions when embedding structs in Go.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3