在PostgreSQL数据库中,我有一个表:
| ORGANIZATION_ID | FACTOR_IDS | CALCULATION_VALUES |
|-----------------|--------------|---------------------|
| 1 | {1,2,3,4,5} | {0,66.66,50,100,80} |
| 2 | NULL | NULL |
| 1 | {6,7,8,9,10} | {0,77.77,60,110,90} |在Go中,我对表进行了查询,然后尝试使用Scan方法。不幸的是,我得到了一个错误:
Trace: runtime error: invalid memory address or nil pointer dereference我的代码:
type Entry struct {
OrganizationID int
FactorIDS pq.Int64Array
CalculationValues pq.Float64Array
}
rows, err = database.DBGORM.Raw(`SELECT * FROM ANALYTICS`, ID).Rows()
if err != nil {
utils.Logger().Println(err)
return
}
defer rows.Close()
for rows.Next() {
var entry *Entry
if err = rows.Scan(&entry.OrganizationID, &entry.FactorIDS, &entry.CalculationValues); err != nil {
utils.Logger().Println(err) // <- RAISE ERROR
return
}
if entry.FactorIDS != nil {
for index, value := range factorID {
// some code here
}
}
}我如何解决这个问题?
此外,如果我将类型从pq.Int64Array更改为*pq.Int64Array,Go编译器会为上面的代码显示错误:Cannot range over data *pq.Int64Array。
发布于 2019-07-29 12:56:51
nil指针取消引用位于entry上。通过将entry从指针更改为值来修复:
for rows.Next() {
var entry Entry // <--- change on this line
... remaining code as in question
}发布于 2019-07-29 15:23:56
它是因为这些&entry.OrganizationID,&entry.FactorIDS,&entry.CalculationValues而恐慌的。因为条目是指针类型的,你还没有初始化它的内存。如果你想要指针类型的结构,你可以这样初始化它:
for rows.Next() {
entry:=new(Entry)
if err = rows.Scan(&entry.OrganizationID, &entry.FactorIDS, &entry.CalculationValues); err != nil {
utils.Logger().Println(err) // <- RAISE ERROR
return
}
if entry.FactorIDS != nil {
for index, value := range factorID {
// some code here
}
}
}https://stackoverflow.com/questions/57247355
复制相似问题