How to Achieve Polymorphism in Go Using Composition?

Susan Sarandon
Release: 2024-11-21 10:42:14
Original
548 people have browsed it

How to Achieve Polymorphism in Go Using Composition?

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"
    // ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template