duanjiwu0324 2015-11-11 01:19
浏览 199
已采纳

如何在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
}
  • 写回答

2条回答 默认 最新

  • dongpang1232 2015-11-11 01:21
    关注

    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)
    

    EDIT: based on some discussion seems like the OP probably wants to do something like below

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?