Home > Backend Development > Golang > How to Implement Polymorphism in Go without Base Types?

How to Implement Polymorphism in Go without Base Types?

Susan Sarandon
Release: 2024-11-17 00:31:03
Original
935 people have browsed it

How to Implement Polymorphism in Go without Base Types?

Understanding Polymorphism in Go

While trying to solve a programming problem involving multiple types of transactions and a shared base type, you may have encountered challenges in implementing polymorphism. Let's delve into the concept of polymorphism and address your specific issue.

In Go, unlike object-oriented languages, polymorphism is limited to interfaces. Interfaces define a set of methods that can be implemented by different types.

In your case, you were attempting to create a "base" type, BaseTX, and two child types, RewardTX and AllowanceTX. These child types had additional fields compared to the base.

The problem arose because you defined a function, logicAndSaveTX, that operates on the TXapi interface. However, this function's implementation operates on the BaseTX type, leading to the exclusion of the additional fields from the child types.

The solution lies in removing the concept of a "base" type. Instead, think of Metadata as common fields shared among transactions. You can declare Metadata as a separate type and embed it into the RewardTX and AllowanceTX types. Each type can then have its own logicAndSaveTX method that modifies specific fields.

Here's an updated example:

type TXapi interface {
    logicAndSaveTX()
}

type Metadata struct {
    Field1 string
    Field2 string
}

type RewardTX struct {
    Metadata 
}

func (tx RewardTX) logicAndSaveTX() {
    // Modify TX-specific fields
    tx.Field1 = "Reward Field 1"
    tx.Field2 = "Reward Field 2"

    // Logic and save metadata shared with AllowanceTX
}

type AllowanceTX struct {
    Metadata 
    AddField string
}

func (tx AllowanceTX) logicAndSaveTX() {
    // Modify TX-specific fields
    tx.Field1 = "Allowance Field 1"
    tx.Field2 = "Allowance Field 2"
    tx.AddField = "Allowance Additional Field"

    // Logic and save metadata shared with RewardTX
}
Copy after login

By embracing composition and defining clear scopes for methods, you can effectively implement polymorphism through interfaces in Go.

The above is the detailed content of How to Implement Polymorphism in Go without Base Types?. 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