Golang 向别处定义的结构添加函数 [英] Golang add function to struct defined elsewhere

查看:48
本文介绍了Golang 向别处定义的结构添加函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 sql.Row 结构上创建一个函数,它将一行扫描到我的结构 ErrorModel 中.这就是我正在做的:

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?

推荐答案

您不能定义非本地类型的方法.根据规范:

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

T 表示的类型称为接收器基类型;它不能是指针或接口类型,并且它必须与方法在同一个包中声明.

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.

(添加了强调.)

您可以做的是创建自己的类型并将导入的类型嵌入:

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
}

这篇关于Golang 向别处定义的结构添加函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆