在struct中循环struct

问题描述 投票:1回答:1

我试图在图形数据库(dgraph)中保存表单数据,我需要在父数据库中迭代另一个结构。

我有几个名字TagQuestion的结构,我有名字words的数组。

我必须用Question数组填充wordsstruct作为数组Tag结构

这就是我想要做的:

type Tag struct {
    Name string
    Count string
}

type Question struct {
    Title string
    Tags []Tag
}

words := []string{"one", "two", "three", "four"}

tagsList := []Tag
for i=0;i<len(words);i++ {
    tagsList = append(tagsList, words[i])
}

q := Question {
    Title: "Kickstart Business with Corporate Leadership",
    Tags: tagsList,
}

我收到错误:“type [] Tag不是表达式”

我需要帮助将“最高”放在“问题”结构值中。

go struct
1个回答
2
投票

要将变量初始化为空切片,您需要[]Tag{},而不是[]Tag。您还可以在单​​词列表中查找更简单的单词,然后您只需要从单词构建标记,例如

words := []string{"one", "two", "three", "four"}

tagsList := []Tag{}
for _, word := range words {
    tagsList = append(tagsList, Tag{Name: word})
}

完整的example on playground

© www.soinside.com 2019 - 2024. All rights reserved.