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)
使用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或测试它,但我从手机输入了这个。
答案 1 :(得分:0)
您不需要为每个字段创建局部变量,只需创建一个结构并使用它来读取数据并使用切片来累积结果:
Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do **not** throw java.util.ConcurrentModificationException ConcurrentModificationException
最好在// 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(¤t.id, ¤t.eventid, ¤t.excel_id, ¤t.userid, ¤t.hallid)
newRs = append(newRs, r)
}
和rows.Next()
后检查错误。