-3

I'm trying to add value to a slice of struct, I have the following struct:

type RelatedSearchItem struct {
    Title      string `json:"title"`
    Navigation string `json:"url"`
}

Now I create a slice of this struct :

relatedSearchItem := []models.RelatedSearchItem{}

And finally I add data to his fields :

    for i := 0; i < len(questions); i++ {
        relatedSearchItem[i].Title = questions[i]
        relatedSearchItem[i].Navigation = URL[i]
    }

But when I do this I'm out of the range of the slice so my app crash, how can I add data to this slice of struct and without a fixed length ?

I immediately think about append but here I'm not adding a slice to another I just want to build it with my data.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Romain P
  • 55
  • 1
  • 1
  • 11
  • Does this answer your question? [Golang append an item to a slice](https://stackoverflow.com/questions/20195296/golang-append-an-item-to-a-slice) – Riwen May 31 '21 at 15:40
  • Not exactly, because i want to add value to the field of a slice of struct – Romain P May 31 '21 at 15:57

1 Answers1

3

Use append:

for i := 0; i < len(questions); i++ {
  relatedSearchItems=append(relatedSearchItems, RelatedSearchItem{
          Title: questions[i],
          Navigation: URL[i],
         })
    }
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Ah thank you, I didn't think to use append like this ! I was writing `relatedSearchItems = append(relatedSearchItems, relatedSearchItem[i].Title)` but that was not possible. – Romain P May 31 '21 at 15:54