N
N
Nube2018-05-31 20:54:58
go
Nube, 2018-05-31 20:54:58

Why is it impossible to write data from the database to the fields of nested structures?

Good day! There is an IndexPage structure in which the Post structure is nested. I'm trying to fill it with data from the database, but I get the error "runtime error: invalid memory address or nil pointer dereference", but if I try to fill the Post structure directly, everything goes well.
I can’t write to Post right away. In addition to this structure, there are more that need to be invested in one - IndexPage
Actually the code itself. Right now IndexPage has only one nested structure.

var (
    index = make(map[int]*model.IndexPage)
)
func UpdateIndexPage() *(map[int]*model.IndexPage){

  result, err := db.Query(sqlTopPost2)
  if err != nil {
    log.Println(err)
  }
  posts := make([]*model.IndexPage, 0)

  //Run In Cycle
  for result.Next() {
    post := new(model.IndexPage)
    err := result.Scan(&post.Post.ID,&post.Post.Title,&post.Post.Description,&post.Post.Rating,&post.Post.Author,&post.Post.ImageLink)

    if err != nil{
      fmt.Println(err,"Gero")
      continue
    }

    posts = append(posts,post)

  }
  if err = result.Err(); err != nil {
    log.Println(err)

  }

  for _, post := range posts{
    index[post.Post.ID] = post
  }

  return &index

}

The error crashes on the line result.Scan

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nube, 2018-06-01
@Nube

It was all about structure. Instead of

type Data strcut {
 Dt      *Img
}
type Img strcut {
 Link  string
}
использовать 
type Data strcut {
 Img
}

A
Andrey Tsvetkov, 2018-06-01
@yellow79

Where do you create the index variable that the function returns? And it will be easier if you specify the line that the error points to

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question