Weiwei Weiwei - 3 years ago 157
MySQL Question

Go lang map multi result

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.

Answer Source

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(&current.id, &current.eventid, &current.excel_id, &current.userid, &current.hallid)
    newRs = append(newRs, r)
}

And also it is better to check for errors after rows.Next() and rows.Scan(...).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download