douchunxian9740 2016-07-14 12:15
浏览 65
已采纳

处理程序中的Golang抽象,以避免代码重复

I am trying to implement abstraction in golang I am using gorm orm library and gin framework

Base Class

type Base struct {
  Context *gin.Context // Passing gin request
}

func (b *Base ) Add() {
   err := b.Context.BindJSON(b)
   if err != nil {
     // handling error here
   }
   gorm.db.Create(b) // Here I am adding base data to database
}

Child Class

type Shopper struct { 
   Base  // Embedding Base struct
   Name string,
   Address string,
   ContactNo int
}

Handler

 func handler (c *gin.Context) {
  s := new(Shopper)
  s.Context = c
  s.Add()  // Here I am expecting Add() method should bind JSON to shopper struct
           // entry to database using gorm
 }

Add() method is not taking any property which shopper struct has.

Here I just want to avoid code duplication in each handler which just takes json from request body and add to respective database using gorm

  • 写回答

1条回答 默认 最新

  • doumi1884 2016-07-14 20:31
    关注

    You can't because Go does not have inheritance.

    Let me repeat: Go does not have inheritance, so please unlearn this "base" and "child" stuff when working with Go.

    The reason your code does not work is that while the method set of an embedded type is indeed "lifted" and merged into the method set of the type which embeds it, when any of such methods is called its receiver is the value of the embedded type and not the value of the enclosing type.

    IOW your Add() method always receives values of type Base

    If the enclosing type has a method which has the same name as a method of the embedded type, and you call such method on a value of the enclosing type, the method of the enclosing type will be called. So there's no overloading but there's "overriding" if you want.

    What I'd do in your situation is stop thinking in OOP and wrote a function rather than a method (untested):

    func add(any interface{}, ctx *gin.Context) {
       err := ctx.BindJSON(any)
       if err != nil {
         // handling error here
       }
       gorm.db.Create(any) // Here I am adding base data to database
    }
    

    Then in your handler:

    func handler (c *gin.Context) {
      s := new(Shopper)
      s.Context = c
      add(s, c)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格