The concept of inheritance in object-oriented languages like C allows for the creation of complex type hierarchies. However, Go, a language that lacks classes and inheritance, poses a unique challenge when it comes to representing hierarchical structures.
In the Go compiler, a hierarchy of types is represented using interfaces with empty methods. While the Go FAQ suggests this approach to explicitly guarantee interface implementation, it can lead to an excessive number of empty methods.
Go supports embedding both structs and interfaces. Empty methods are introduced to ensure that types explicitly implement interfaces, thereby preventing type assignment incompatibilities.
An alternative approach is to create struct implementations that embed higher-level types. This allows for automatic inheritance of method sets, reducing the need for empty methods.
For instance, consider a hierarchy:
Object --Immovable ----Building ----Mountain --Movable ----Car ----Bike
The Object interface and implementation:
type Object interface { object() } type ObjectImpl struct {} func (o *ObjectImpl) object() {}
The Immovable interface and implementation:
type Immovable interface { Object immovable() } type ImmovableImpl struct { ObjectImpl // Embedded } func (i *ImmovableImpl) immovable() {}
The Building struct:
type Building struct { ImmovableImpl // Embedded }
By embedding the ImmovableImpl struct, Building automatically inherits the immovable() method without the need for an additional empty method. This technique minimizes the number of empty methods required, especially as the hierarchy grows or interfaces contain more than one method.
The above is the detailed content of How Can We Idiomatically Create Complex Hierarchies of Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!