Reputation: 13712
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?
Upvotes: 1
Views: 1954
Reputation: 36259
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
}
Upvotes: 9