Search code examples
gobeego

How to add a method for different structs which have one common field in golang


I'm using beego/orm for my app. Here I have 2 models

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

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

I need to add a Save() method for each struct. In general, I can create an Base struct and mixin it into ModelA and ModelB, but the orm would not work.

Is there any better solution?

edit1: Giving Save() code here to make question more clear

func (this *ModelA) Save() error {
    o := orm.NewOrm()
    guid := guidlib.Generate()
    this.Guid = guid
    _, err := o.Insert(this)
    return err
}

func (this *ModelB) Save() error {
    o := orm.NewOrm()
    guid := guidlib.Generate()
    this.Guid = guid
    _, err := o.Insert(this)
    return err
}

Solution

  • Yes. Define an interface. Also, hate to nitpick, while I'm pretty sure you're talking about embedding there isn't a 'mixin' concept that exists in Go. Here's some pseudo code that demonstrates the constructs.

    type Savable interface {
           Save()
    }
    
    // satisfies Savable for ModelA
    func (a ModelA) Save() {
          // do something
    }
    
    var i Savable
    i = SomeMethodThatRetunsMyModel()
    i.Save()
    SomeOthermMethodThatAcceptsASavableAndCallesSave(i)
    

    The embedding approach:

    type ModelA struct {
        ModelC
        FiledA string
    }
    
    type ModelB struct {
        ModelC
        FiledB string
    }
    
    type ModelC struct {
        Guid string `orm:"pk"`
    }
    
    func (this ModelC) Save() error {
        o := orm.NewOrm()
        guid := guidlib.Generate()
        this.Guid = guid
        _, err := o.Insert(this)
        return err
    }
    

    However, note that o.Insert(this) is not going to insert any fields that aren't defined on ModelC. As I mentioned in my comment below the type of inheritance structure that might be used where models A and B would reimplement Save calling the base classes method upfront doesn't really work well in Go.

    The rules for method resolution with embedded types aren't completely clear and can be confusing. You could define one version of Save in the embedded structs, redefine it in the embedor and even call it within that method however it doesn't really make much sense to do. I would make a point to avoid embedding if you're still going to have to statically reference the embedded type. For example if I have ModelA embedding ModelC and in the broader scope I'm having to do ModelA.ModelC.SomeMethodThatIhaveToReferencExplicitlyToEnsureItsCalled() then I'm probably making poor use of the feature.