How to Implement Shared Methods for Go Structs with Common Fields?

Linda Hamilton
Release: 2024-11-21 07:47:09
Original
645 people have browsed it

How to Implement Shared Methods for Go Structs with Common Fields?

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

When dealing with multiple structs that share a common field, the need often arises to implement a common method for these structs. While inheritance or mixins may seem like viable approaches, they face limitations in Go.

One approach is to define an interface that specifies the desired method, as shown below:

type Savable interface {
  Save()
}

// Satisfy Savable for ModelA
func (m ModelA) Save() {
  // Implement Save() for ModelA
}

var i Savable
i = SomeMethodThatReturnsMyModel()
i.Save()  // Call Save() on the implementing type
SomeOtherMethodThatAcceptsASavableAndCallsSave(i)
Copy after login

Alternatively, embedding can be used to achieve code reuse. However, this requires careful consideration, as the embedded fields will not be inserted when calling o.Insert(this) unless they are also defined in the embedded type.

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

func (m ModelC) Save() {
  // Implement Save() for ModelC
}

type ModelA struct {
  ModelC
  FiledA string
}

type ModelB struct {
  ModelC
  FiledB string
}
Copy after login

It's important to remember that embedding does not support inheritance-based method overriding. Redefining Save() in the embedded struct and calling the base class's method within the redefinition is not considered a good practice in Go.

When considering between the two approaches, it's essential to evaluate the specific requirements and trade-offs involved. The interface approach provides greater flexibility, while embedding can offer performance advantages but requires careful consideration of the embedded field's behavior.

The above is the detailed content of How to Implement Shared Methods for Go Structs with Common 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