英文:
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)
// 这里是我想要做的
newR = append(newR, struct {
id string
eventid string
excel_id string
userid string
hallid string
}{})
newR[i].id = id
newR[i].eventid = eventid
newR[i].excel_id = excel_id
newR[i].userid = userid
newR[i].hallid = hallid
i++
}
最终我得到了一个错误消息 "runtime error: index out of range"
在 /myapp/app/controllers/app.go(大约在第122行)
newR[i].id = id
有什么建议或提示将会有所帮助。谢谢。
英文:
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.
答案1
得分: 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
或测试它,但我是从我的手机上输入的。
英文:
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.
答案2
得分: 0
你不需要为每个字段创建本地变量,只需创建一个结构体并使用它来读取数据,并使用切片来累积结果:
// 结构体定义必须在函数体外部
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, current)
}
// 在 `rows.Next()` 和 `rows.Scan(...)` 之后最好检查错误
请注意,我已经将代码中的 &
替换为 &
,因为它是 HTML 实体编码的表示形式。
英文:
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(...)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论