douchunxian9740 2016-07-14 12:15
浏览 65


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


 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 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 Spring MVC项目,访问不到相应的控制器方法
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal
  • ¥15 STM32CubeIDE下载程序报错
  • ¥15 微信好友如何转变为会员系统?(相关搜索:小程序)
  • ¥15 c# 直接使用c++ 类库文件
  • ¥15 一个主机电脑有两个显示器,当前有两个软件主体是网页html打包的exe程序,如何通过cmd命令bat同时打开软件一个在主屏幕显示,另外一个软件在2副屏幕上显示