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

Susan Sarandon
Release: 2024-11-19 08:49:02
Original
806 people have browsed it

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

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()
}
Copy after login

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

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

func (b ModelB) Save() {
    // Implementation for ModelB
}
Copy after login

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

var i Savable
i = ModelA{}
i.Save()
Copy after login

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

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

func (c ModelC) Save() {
    // Implementation
}
Copy after login

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!

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