简体   繁体   English

如何在Go中循环遍历结构切片?

[英]How do I loop over a struct slice in Go?

I recently parsed a json message to a struct array like this: 我最近将json消息解析为如下所示的struct数组:

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... 当我编译它时,编译器说x.Type和x.Number未定义...

How can I fix it? 我该如何解决?

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 参考: 对于语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM