Idiomatic Implementation of Complex Structural Hierarchies in Go
Go's lack of inheritance and support for embedding make the representation of complex structural hierarchies non-trivial. The Go compiler's use of empty methods in its AST implementation has raised questions about its efficacy.
Understanding Empty Methods
While not essential, empty methods serve two key purposes:
Leveraging Embedding
Embedding allows a struct to incorporate another struct's fields and methods, creating a form of inheritance. By embedding the appropriate structs in a hierarchical manner, we can reduce the need for empty methods.
Object-Immovable-Movable Hierarchy
Consider the following hierarchy:
Object --Immovable ----Building ----Mountain --Movable ----Car ----Bike
Object Implementation:
type Object interface { object() } type ObjectImpl struct {} func (o *ObjectImpl) object() {}
Immovable Implementation:
type Immovable interface { Object immovable() } type ImmovableImpl struct { ObjectImpl // Embedded Object implementation } func (i *ImmovableImpl) immovable() {}
Building Implementation:
type Building struct { ImmovableImpl // Embedded Immovable implementation // Additional Building-specific fields }
Movable Implementation:
type Movable interface { Object movable() } type MovableImpl struct { ObjectImpl // Embedded Object implementation } func (m *MovableImpl) movable() {}
Car Implementation:
type Car struct { MovableImpl // Embedded Movable implementation // Additional Car-specific fields }
Example Usage:
// Building cannot be assigned to a Movable-typed variable because it does not implement the Movable interface. var movable Movable = Building{} // However, it can be assigned to an Object-typed variable because both Immovable and Movable implement Object. var object Object = Building{}
Advantages of Embedding:
The above is the detailed content of How Can Embedding Improve Complex Structural Hierarchy Implementation in Go?. For more information, please follow other related articles on the PHP Chinese website!