douchang8219 2015-06-12 14:03
浏览 24
已采纳

Golang将功能添加到其他地方定义的结构

I want to create a function on the sql.Row struct that scans a row into my struct ErrorModel. This is what I am doing:

func (row *sql.Row) ScanErrorModel(mod *model.ErrorModel, err error) {
    err = row.Scan(&mod.MessageId, &mod.ServiceName, &mod.EventName,
      &mod.Hostname, &mod.Message, &mod.CriticalRate, &mod.Extra, &mod.Timestamp)
    return
}

func (dao *ErrorsDAO) Fetch(id string) (mod *model.ErrorModel, err error) {
    row := dao.DB.QueryRow("select * from errors where message_id=$1", id) 
    return row.ScanErrorModel()
}

But I am getting a compiler error here:

row.ScanErrorModel undefined (type *sql.Row has no field or method ScanErrorModel)

Is it impossible to add a function onto a struct that is defined somewhere else like this? Or am I just making a syntax error?

  • 写回答

1条回答 默认 最新

  • dongtie0929 2015-06-12 14:17
    关注

    You cannot define methods of non-local types. As per Spec:

    The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method.

    (Emphasis added.)

    What you can do is create your own type and embed the imported type into it:

    // Has all methods of *sql.Row.
    type myRow struct {
        *sql.Row
    }
    
    func (row myRow) ScanErrorModel(mod *model.ErrorModel, err error) {
        err = row.Scan(&mod.MessageId, &mod.ServiceName, &mod.EventName,
          &mod.Hostname, &mod.Message, &mod.CriticalRate, &mod.Extra, &mod.Timestamp)
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看