Go's approach to representing hierarchical relationships among structs, exemplified by the Go compiler's AST implementation, revolves around using interfaces with empty methods. This raises the question of whether this method is truly idiomatic and straightforward.
Empty Methods for Interface Implementation
Go's interfaces are sets of method signatures. By adding empty methods to an interface, the intention to implement that interface is explicitly stated. This is particularly useful for types that do not implicitly implement the interface due to having a compatible method set.
Enforcing Distinct Type Distinctions
Empty methods play a vital role in differentiating types within hierarchies. For example, if Immovable and Movable were to share the same method set, an object of one type could be assigned to a variable of the other type, violating the intended distinction. By adding distinct empty methods to each interface, this assignment is prevented.
Reducing Empty Methods with Embedded structs
While empty methods can serve their purpose, they can also lead to a proliferation of such methods. To address this, it is possible to define custom struct implementations and embed them within each other. This allows the methods of parent implementations to be "inherited," reducing the need for empty methods.
Example Implementation
Using the example hierarchy, we create a struct implementation for each type:
<br>type ObjectImpl struct {}</p> <p>func (o *ObjectImpl) object() {}</p> <p>type ImmovableImpl struct {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">ObjectImpl
}
func (o *Immovable) immovable() {}
type Building struct {
ImmovableImpl
}
Here, Building automatically becomes an Immovable object because it embeds the ImmovableImpl struct.
Conclusion
The use of empty methods in Go's AST hierarchy is a matter of convention, but it serves to emphasize the need for explicit interface implementation and type distinction. While embedded structs can reduce the number of empty methods, the choice of approach depends on the specific requirements and preferences of the developer.
The above is the detailed content of How Can We Idiomatically Create Complex Struct Hierarchies in Go?. For more information, please follow other related articles on the PHP Chinese website!