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

DDD
Release: 2024-10-30 16:45:02
Original
454 people have browsed it

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:

<code class="go">type Job struct {
    Command string
    *log.Logger
}</code>
Copy after login

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.

<code class="go">type Job struct {
    Command string
    log.Logger
}</code>
Copy after login

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.

The above is the detailed content of Embedding Structs in Go: Pointer or Value? When to Use 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!