How to Implement a Shared Method for Struct with a Common Field in Go
When dealing with multiple structs that share a common field, the need often arises to implement a common method for these structs. While inheritance or mixins may seem like viable approaches, they face limitations in Go.
One approach is to define an interface that specifies the desired method, as shown below:
type Savable interface { Save() } // Satisfy Savable for ModelA func (m ModelA) Save() { // Implement Save() for ModelA } var i Savable i = SomeMethodThatReturnsMyModel() i.Save() // Call Save() on the implementing type SomeOtherMethodThatAcceptsASavableAndCallsSave(i)
Alternatively, embedding can be used to achieve code reuse. However, this requires careful consideration, as the embedded fields will not be inserted when calling o.Insert(this) unless they are also defined in the embedded type.
type ModelC struct { Guid string `orm:"pk"` } func (m ModelC) Save() { // Implement Save() for ModelC } type ModelA struct { ModelC FiledA string } type ModelB struct { ModelC FiledB string }
It's important to remember that embedding does not support inheritance-based method overriding. Redefining Save() in the embedded struct and calling the base class's method within the redefinition is not considered a good practice in Go.
When considering between the two approaches, it's essential to evaluate the specific requirements and trade-offs involved. The interface approach provides greater flexibility, while embedding can offer performance advantages but requires careful consideration of the embedded field's behavior.
The above is the detailed content of How to Implement Shared Methods for Go Structs with Common Fields?. For more information, please follow other related articles on the PHP Chinese website!