Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top