去郎地图多结果

时间:2017-07-26 03:01:43

标签: mysql dictionary go

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

任何建议或提示都会有所帮助。感谢。

2 个答案:

答案 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(&current.id, &current.eventid, &current.excel_id, &current.userid, &current.hallid) newRs = append(newRs, r) } rows.Next()后检查错误。