gpt4 book ai didi

for-loop - 我如何在 Go 中遍历结构 slice ?

转载 作者:IT王子 更新时间:2023-10-29 01:49:22 25 4
gpt4 key购买 nike

我最近将一条 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)

//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
}
}
}

当我编译它时,编译器说 x.Type 和 x.Number 未定义...

我该如何解决?

最佳答案

修复错误

undefined: i
x.Type undefined (type int has no field or method Type)
x.Number undefined (type int has no field or method Number)

改变

for x := range p.Fruits

for i, x := range p.Fruits

引用:For statements

关于for-loop - 我如何在 Go 中遍历结构 slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22110089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com