How do I loop over a struct slice in Go?

huangapple go评论92阅读模式
英文:

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

huangapple
  • 本文由 发表于 2014年3月1日 12:25:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/22110089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定