Home >Backend Development >Golang >How to Efficiently Implement a Save Method Across Dissimilar Go Structs with Shared Fields?

How to Efficiently Implement a Save Method Across Dissimilar Go Structs with Shared Fields?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 12:56:38670browse

How to Efficiently Implement a Save Method Across Dissimilar Go Structs with Shared Fields?

How to Append a Save Method to Dissimilar Structs with Shared Fields

Consider the following context:

type ModelA struct {
    Guid string `orm:"pk"`
    FiledA string
}

type ModelB struct {
    Guid string `orm:"pk"`
    FiledB string
}

The need arose to introduce a Save() method for both structs (ModelA and ModelB). While it's possible to create a common base struct and embed it into ModelA and ModelB, this approach is not viable due to ORM limitations.

Alternative Approach: Implementing an Interface

Designate a common interface for saving data, such as Savable, as seen below:

type Savable interface {
   Save()
}

Implement the Save() method for each struct, ensuring that they satisfy the Savable interface:

func (a ModelA) Save() {
   // Save logic for ModelA
}

func (b ModelB) Save() {
   // Save logic for ModelB
}

With this structure in place, you can operate on instances of either struct through the Savable interface:

var i Savable
i = SomeMethodThatRetunsMyModel()
i.Save()
SomeOthermMethodThatAcceptsASavableAndCallesSave(i)

Implementation Using Embedding

Alternatively, you can also opt for an embedding approach by defining a base ModelC with the common field (Guid):

type ModelA struct {
   ModelC
   FiledA string
}

type ModelB struct {
   ModelC
   FiledB string
}

type ModelC struct {
   Guid string `orm:"pk"`
}

func (c ModelC) Save() error {
   // Save logic for ModelC
   return nil
}

However, note that this method will only save fields defined in ModelC.

Considerations

It's important to note the limitations of both approaches:

  • The embedding approach may not be suitable if you need to statically reference embedded types.
  • The interface approach provides more flexibility but may result in code duplication.

Ultimately, the best solution depends on the specific requirements of your application.

The above is the detailed content of How to Efficiently Implement a Save Method Across Dissimilar Go Structs with Shared Fields?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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