How to Implement a Common Method for Structs with a Shared Field in Go
When working with structs that share a common field, it may be desirable to add a method that can be applied to all of them. This question explores this scenario in the context of Beego/ORM, where two structs, ModelA and ModelB, need a Save() method.
Proposed Solutions
<br>type Savable interface {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Save()
}
func (a ModelA) Save() {
// Implementation for ModelA
}
func (b ModelB) Save() {
// Implementation for ModelB
}
<br>type ModelC struct {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">Guid string `orm:"pk"`
}
func (c ModelC) Save() error {
// Implementation for ModelC
}
type ModelA struct {
ModelC FiledA string
}
type ModelB struct {
ModelC FiledB string
}
Caution with Embedding
It should be noted that embedding has certain limitations. While the embedded Save() method will be available to ModelA and ModelB, any additional fields specific to these structs will not be automatically included in the Save() operation.
Conclusion
The most appropriate solution depends on the specific requirements of the system. If the Save() implementation varies significantly between ModelA and ModelB, the interface approach provides greater flexibility. However, if they share a common implementation, embedding may be more efficient since it eliminates the need for redundant code.
The above is the detailed content of How to Implement a Common `Save()` Method for Go Structs Sharing a Field?. For more information, please follow other related articles on the PHP Chinese website!