【问题标题】:How to add value to a slice of struct如何为结构切片添加值
【发布时间】:2021-05-31 15:35:17
【问题描述】:

我正在尝试为结构切片添加价值,我有以下结构:

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,但在这里我不会将切片添加到另一个切片上,我只是想用我的数据构建它。

【问题讨论】:

标签: go struct slice


【解决方案1】:

使用append:

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

【讨论】:

  • 啊,谢谢,我没想到要像这样使用 append !我正在写 relatedSearchItems = append(relatedSearchItems, relatedSearchItem[i].Title) 但那是不可能的。
猜你喜欢
  • 2020-02-03
  • 2014-08-24
  • 2021-04-14
  • 1970-01-01
  • 2017-02-19
  • 2020-09-12
  • 2012-01-27
  • 1970-01-01
  • 2018-06-05
相关资源
最近更新 更多