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++
}
Eventually I got an error msg "runtime error: index out of range" In /myapp/app/controllers/app.go (around line 122)
newR[i].id = id
Any suggestions or tips will helps. Thanks.
You do not need to create a local variables for each field, just create a struct and use it to read data into and use a slice to accumulate results:
// 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)
}
And also it is better to check for errors after rows.Next()
and rows.Scan(...)
.
Use append to add a new element and initialize a not yet allocated slice.
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)
...
Sorry for not fmt or test it out but I typed this from my mobile.