在结构中声明和使用 map

Declarate and using map in structs

我对 golang 非常菜鸟,几天前才开始。

实际上我正在尝试做一个简单的练习来习惯 golang 语法。

我在 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)
}

我试着做一个简单的结构,但我知道。如果我使用接口,问题就解决了,但如果在接下来的步骤中,我将需要在结构中使用地图...

PS:这是我使用过的示例结构:

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
}

最后的问题是:

如何在结构内部的参数中使用映射并将其写在声明中?

结构字段值的复合文字表达式中必须使用类型 (map[int]string):

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

复合文字表达式中的类型只能在切片元素(与 []survey.Question 的元素一样)、映射键和映射值上省略。

Run it on the Go playground.