Home >Backend Development >Golang >How Can I Efficiently Initialize Embedded Structs in Go Using Composite Literals?

How Can I Efficiently Initialize Embedded Structs in Go Using Composite Literals?

Barbara Streisand
Barbara StreisandOriginal
2024-12-15 16:15:14573browse

How Can I Efficiently Initialize Embedded Structs in Go Using Composite Literals?

Using Nested Composite Literals to Initialize Composed Structs

In Go, initializing a composed struct can be tricky when embedding other structs. The original syntax of child := Child{ ID: id, a: a, b: b } may result in an error due to the inability to directly initialize the embedded field ID.

To overcome this issue and maintain encapsulation, use nested composite literals:

child := Child{
    Base: Base{ID: id}, // Initialize the embedded struct
    a: a,
    b: b,
}

This approach allows initializing the composed struct in a single expression while preserving encapsulation by nesting the embedded struct initialization.

Another solution, as hinted in the question, is to use factory methods like NewFoo(). However, nested composite literals provide a more concise and safe alternative.

Proposed Change in Composite Literals

Go issue 9859 proposes a change to the syntax of composite literals to support directly initializing embedded fields. This change would enable the original syntax of child := Child{ ID: id, a: a, b: b }.

Encapsulation Considerations

Embedding structs is not a strict encapsulation feature in Go. While it allows indirect access to embedded fields, it does not enforce it. The code can still directly access child.Base.ID in addition to using child.ID. So, the responsibility of encapsulation ultimately lies with the application's design and usage.

The above is the detailed content of How Can I Efficiently Initialize Embedded Structs in Go Using Composite Literals?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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