dictionary - 在结构中声明和使用映射

标签 dictionary go struct type-declaration golang-migrate

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

我试着做一个简单的结构,但我知道。如果我使用接口(interface),这个问题就解决了,但是如果在接下来的步骤中我需要在结构中使用映射......

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 并将其写在声明中?

最佳答案

类型 ( 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",
        },
    },
}

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

Run it on the Go playground .

关于dictionary - 在结构中声明和使用映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58368348/

相关文章:

python - 如何将字典的键值对收集到 Python 中的一个大字典中?

java - 如何初始化Map<Integer, Map<Integer, Float>>?

go - 通过函数分配Golang

c++ - C++中结构的选择排序

我可以制作一个结构,其中超过一半的空间是填充的吗?

python - 如何将三个列表压缩到一个嵌套的字典中

database - 免费/开放的翻译数据库?

golang 模板中的 HTML 表单提交

go - GoLand 中如何查看当前包的名称?

c++ - 如何将 vector 列表存储为全局变量?