如何为结构切片添加值

How to add value to a slice of struct

我正在尝试为结构的一部分添加值,我有以下结构:

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

现在我创建了这个结构的一个片段:

relatedSearchItem := []models.RelatedSearchItem{}

最后,我将数据添加到他的字段中:

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

但是当我这样做时,我超出了切片的范围,所以我的应用程序崩溃了,我如何向这个结构切片添加数据并且没有固定长度?

我立即想到了 append,但在这里我不会向另一个切片添加切片,我只是想用我的数据构建它。

使用append:

for i := 0; i < len(questions); i++ {
  relatedSearchItems=append(relatedSearchItems, RelatedSearchItem{
          Title: questions[i],
          Navigation: URL[i],
         })
    }