简体   繁体   中英

Looping struct inside struct

I am trying to save form data in graph database (dgraph ) for which I need to iterate another struct inside parent struct.

I have couple of struct with name Tag and Question and I have array with name words .

I have to fill the Question struct with words array as array Tag struct

This is what I am trying to do:

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,
}

I am getting error: "type []Tag is not an expression"

I need help in putting "tallest" in "Question" struct value.

To initialize a variable to an empty slice, you want []Tag{} , not []Tag . You can also range over the list of words which is a bit easier, and then you just need to construct your Tag from the word, eg

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

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

Full example on playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM