Home >Backend Development >Golang >How to Implement a Common `Save()` Method for Go Structs Sharing a Field?

How to Implement a Common `Save()` Method for Go Structs Sharing a Field?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 07:03:11372browse

How to Implement a Common `Save()` Method for Go Structs Sharing a Field?

How to Implement a Common Method for Structs with a Shared Field in Go

When working with structs that share a common field, it may be desirable to add a method that can be applied to all of them. This question explores this scenario in the context of Beego/ORM, where two structs, ModelA and ModelB, need a Save() method.

Proposed Solutions

  • Interface Definition: Define an interface called Savable that declares the Save() method. Implement this interface for both ModelA and ModelB to allow them to utilize the Save() functionality.

<br>type Savable interface {</p>
<pre class="brush:php;toolbar:false">Save()

}

func (a ModelA) Save() {

// Implementation for ModelA

}

func (b ModelB) Save() {

// Implementation for ModelB

}

  • Embedding: Create a base struct called ModelC that contains the shared Guid field. Embed this struct into ModelA and ModelB. Define the Save() method in ModelC to make it available to both ModelA and ModelB.

<br>type ModelC struct {</p>
<pre class="brush:php;toolbar:false">Guid string `orm:"pk"`

}

func (c ModelC) Save() error {

// Implementation for ModelC

}

type ModelA struct {

ModelC
FiledA string

}

type ModelB struct {

ModelC
FiledB string

}

Caution with Embedding

It should be noted that embedding has certain limitations. While the embedded Save() method will be available to ModelA and ModelB, any additional fields specific to these structs will not be automatically included in the Save() operation.

Conclusion

The most appropriate solution depends on the specific requirements of the system. If the Save() implementation varies significantly between ModelA and ModelB, the interface approach provides greater flexibility. However, if they share a common implementation, embedding may be more efficient since it eliminates the need for redundant code.

The above is the detailed content of How to Implement a Common `Save()` Method for Go Structs Sharing a Field?. 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