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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分