Problem Statement
Creating a hierarchical structure of structs can be challenging in Go due to its lack of explicit inheritance. The Go compiler's AST implementation uses empty methods to represent interfaces, which raises questions about its idiomatic nature and potential complexity.
Idiomatic Solution
Although Go does not support traditional inheritance, it features alternative constructs for representing hierarchies:
type Object interface { object() } type ObjectImpl struct {} func (o *ObjectImpl) object() {} type Immovable interface { Object immovable() } type ImmovableImpl struct { ObjectImpl // Embed ObjectImpl } func (o *Immovable) immovable() {} type Building struct { ImmovableImpl // Embed ImmovableImpl // Building-specific fields }
In this approach, Building automatically inherits the methods from Object and Immovable without the need for explicit empty methods.
Reducing Empty Methods
While empty methods are useful for documenting and enforcing type constraints, they can be reduced by using method embedding:
In summary, idiomatic struct hierarchy creation in Go involves carefully using embedded interfaces and method embedding to establish type relationships and enforce constraints.
The above is the detailed content of How Can I Idiomatically Create Hierarchical Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!