Initializing Composed Structs in Go
Composing structs in Go involves embedding one struct within another. While this technique offers code organization and reuse benefits, it can also introduce initialization challenges.
When initializing a composed struct, directly accessing the embedded struct's fields may not be possible. Consider the following code example:
type Base struct { ID string } type Child struct { Base a int b int } // Error: unknown field 'ID' in struct literal of type Child // child := Child{ ID: id, a: a, b: b }
In this example, attempting to initialize the ID field directly in the Child struct literal fails due to field inaccessibility. To work around this issue, one must first initialize the Child struct without an ID and then set ID separately.
However, this approach compromises encapsulation by exposing the internal structure of the Child struct to its users. To avoid this, Go provides a method for initializing composed structs safely: nested composite literals.
Using Nested Composite Literals
Nested composite literals allow you to initialize embedded struct values within a single expression:
child := Child{Base: Base{ID: id}, a: a, b: b}
In this example, the Base struct is initialized first, with the ID field set to the desired value. The resulting Base struct is then used to initialize the Child struct.
Alternative Approach
Go issue 9859 proposes a change that would simplify the initialization of embedded structs. This change would allow the Child{ ID: id, a: a, b: b } expression, making it consistent with field access for embedded types.
Encapsulation Considerations
It's important to note that embedded types do not provide true encapsulation in Go. Applications can still directly access the embedded struct's fields, bypassing the enclosing struct's methods. Therefore, consider the need for encapsulation carefully when designing your structs.
The above is the detailed content of How to Properly Initialize Composed Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!