2017-07-26 68 views
0
var newR[] struct { 
     id string 
     eventid string 
     excel_id string 
     userid string 
     hallid string 
} 

i := 0 
for rows.Next() { 
    var id, eventid, excel_id, userid, hallid string 
    err = rows.Scan(&id, &eventid, &excel_id, &userid, &hallid) 

    // Here is what I want to do 
    newR[i].id = id 
    newR[i].eventid = eventid 
    newR[i].excel_id = excel_id 
    newR[i].userid = userid 
    newR[i].hallid = hallid 
    i++ 
} 

最后收到错误消息“运行时错误:索引超出范围” 在/myapp/app/controllers/app.go(围绕线122)转到郎映射多结果

newR[i].id = id 

任何建议或提示将有所帮助。谢谢。

+0

你缺少问题中的关键信息,即你​​如何创建切片。我猜你对于你想存储的数据量来说太小了。 –

回答

0

你并不需要创建一个局部变量为每个字段,只需创建一个结构,并用它来的数据读入和使用切片累积结果:

// struct definition must be out of functions body 
type newR struct { 
    id string 
    eventid string 
    excel_id string 
    userid string 
    hallid string 
} 

var newRs []newR 
for rows.Next() { 
    var current newR 
    err = rows.Scan(&current.id, &current.eventid, &current.excel_id, &current.userid, &current.hallid) 
    newRs = append(newRs, r) 
} 

而且还最好是检查对于rows.Next()rows.Scan(...)之后的错误。

0

使用append添加一个新元素并初始化尚未分配的片。

newElement := struct { 
    id string 
    eventid string 
    excel_id string 
    userid string 
    hallid string 
} { 
    id: id, 
    eventid: eventid, 
    excel_id: excel_id, 
    userid: userid, 
    hallid: hallid, 
} 
newR = append(newR, newElement) 

...

对不起,不FMT或对其进行测试,但我打字这个从我的手机。