英文:
How do I loop over a struct slice in Go?
问题
最近我解析了一个 JSON 消息到一个结构体数组中,代码如下:
type Fruit struct {
Number string
Type string
}
type Person struct {
Pid string
Fruits []Fruit
}
func main() {
var p Person
str := `{"pid":"123","fruits":[{"number":"10","type":"apple"},{"number":"50","type":"cherry"}]}`
json.Unmarshal([]byte(str), &p)
// 遍历结构体数组并插入数据库
stmt, err := tx.Prepare(`insert into empi_credentials(PID, type, num) values(?, ?, ?)`)
if err != nil {
panic(err.Error())
}
defer stmt.Close()
for _, x := range p.Fruits {
if _, err = stmt.Exec(p.Pid, x.Type, x.Number); err != nil {
log.Println("stmt.Exec: ", err.Error())
return
}
}
}
当我编译它时,编译器报错说 x.Type 和 x.Number 未定义...
你可以如何修复这个问题?
英文:
I recently parsed a json message to a struct array like this:
type Fruit struct {
Number string
Type string
}
type Person struct {
Pid string
Fruits []Fruit
}
func main() {
var p Person
str := `{"pid":"123","fruits":[{"number":"10","type":"apple"},{"number":"50","type":"cherry"}]}`
json.Unmarshal([]byte(str), &p)
//loop struct array and insert into database
stmt, err := tx.Prepare(`insert into empi_credentials(PID, type, num) values(?, ?, ?)`)
if err != nil {
panic(err.Error())
}
defer stmt.Close()
for x := range p.Fruits {
if _, err = stmt4.Exec(string(i), x.Type, x.Number); err != nil {
log.Println("stmt1.Exec: ", err.Error())
return
}
}
}
When I compile it, the compiler says x.Type and x.Number undefined...
How can I fix it?
答案1
得分: 10
修复错误
undefined: i
x.Type 未定义(类型 int 没有字段或方法 Type)
x.Number 未定义(类型 int 没有字段或方法 Number)
将
for x := range p.Fruits
改为
for i, x := range p.Fruits
参考:For 语句
英文:
To fix errors
undefined: i
x.Type undefined (type int has no field or method Type)
x.Number undefined (type int has no field or method Number)
change
for x := range p.Fruits
to
for i, x := range p.Fruits
Reference: For statements
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论