Understanding Polymorphism in Go: A Composition-Based Approach
In Go, unlike object-oriented languages, polymorphism is achieved through interfaces. When attempting to implement polymorphism, it's important to avoid the concept of "base" classes/types for compositions.
Consider the following problem:
You have a BaseTX struct with fields for transactions and two special types: RewardTX and AllowanceTX. The latter requires an additional AddField. Furthermore, there's a function logicAndSaveTX to perform certain logic before serializing and saving the object.
However, in your current implementation, the AddField property is not being recognized.
Instead of relying on inheritance, a more Go-idiomatic approach is to use composition. The Metadata struct can contain the shared fields used by both RewardTX and AllowanceTX. Each struct can then implement its own logicAndSaveTX method:
func (tx RewardTX) logicAndSaveTX() { // Logic on Metadata fields tx.Field1 = "overwritten" tx.Field2 = "logic done" // ... } func (tx AllowanceTX) logicAndSaveTX() { // Logic on Metadata fields tx.Field1 = "overwritten" tx.Field2 = "logic done" tx.AddField = "more stuff" // ... }
By encapsulating the behavior (methods) within each type, you can avoid the pitfalls of trying to apply operations from one type to another. Instead, you can design clear and maintainable code that operates on the specific types you need to manage.
The above is the detailed content of How to Achieve Polymorphism in Go Using Composition?. For more information, please follow other related articles on the PHP Chinese website!