Home  >  Article  >  Backend Development  >  How to Efficiently Add Shared Functionality to Go Structs with Different Fields?

How to Efficiently Add Shared Functionality to Go Structs with Different Fields?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 08:49:02806browse

How to Efficiently Add Shared Functionality to Go Structs with Different Fields?

How to Add Shared Functionality to Differentiated Go Structs

In Go, you may encounter the need to add a common method to structs that share a specific field, such as the Guid field in the following example:

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

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

Traditionally, one might consider using a base struct and embedding it into ModelA and ModelB. However, this approach may not work seamlessly with the orm library.

A viable solution involves the use of interfaces. By defining an interface, you can declare a common contract that both ModelA and ModelB must implement:

type Savable interface {
    Save()
}

Next, implement the Save() method for both structs:

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

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

Now, you can create a variable of type Savable and assign it to either ModelA or ModelB:

var i Savable
i = ModelA{}
i.Save()

Alternatively, you could use an embedded type approach:

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

type ModelA struct {
    ModelC
    FiledA string
}

type ModelB struct {
    ModelC
    FiledB string
}

In this case, define the Save() method in the embedded ModelC struct:

func (c ModelC) Save() {
    // Implementation
}

While this approach seems straightforward, it's important to note that the o.Insert(this) statement will only insert fields defined on ModelC, not those on ModelA and ModelB.

Therefore, it's recommended to avoid using embedding when you still need to reference the embedded type explicitly. In such cases, the interface approach provides greater flexibility.

The above is the detailed content of How to Efficiently Add Shared Functionality to Go Structs with Different 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