Search code examples
dictionarygostructtype-declarationgolang-migrate

Declarate and using map in structs


I'am so very noob in golang and started only a fews days ago.

Actually I'm trying make a simple exercise for get used to the golang syntax.

I have this in main.go:

package main 

import(
    "fmt"
    // "stringa"
    "main/survey"
)

func main() {
    var questions = []survey.Question{
        {
            Label: "Questão 1",
            Instructions : "Instrução",
            Options : {
                1 : "Op1",
                2 : "Op2",
            },
            Answer: {
                1 : "Op1",
            },
        },
    }
    fmt.Println(questions[0].Label)
}

And I try make a simple structures, but i know. that problems is solveld if I use an interface, but if in next steps I will need using maps in structure...

PS: this is a sample struct I have used:

package survey

import(
    // "fmt"
    // "strings"
    // "strconv"
)

// This is a simple Question in a survey code
type Question struct {
    // This is a label for the quetsion
    Label string
    // This is a instructions and is not required
    Instructions string
    // this is a multiple options answer
    Options map[int]string
    // this is a answer correct response
    Answer map[int]string
}

Finally the question is:

How can I use map in parameters from inside the struct and write this in the declaration?


Solution

  • The type (map[int]string) must be used in a composite literal expression for a struct field value:

    var questions = []survey.Question{
        {
            Label:        "Questão 1",
            Instructions: "Instrução",
            Options: map[int]string{
                1: "Op1",
                2: "Op2",
            },
            Answer: map[int]string{
                1: "Op1",
            },
        },
    }
    

    The type in a composite literal expression can only be elided on slice elements (as it is with the elements of the []survey.Question), map keys and map values.

    Run it on the Go playground.