dictionary - 在单个语句中初始化 Go map

标签 dictionary go initialization

这是我的代码:

var keys map[int]string
keys = make(map[int]string)

keys[1] = "aa"
keys[2] = "ab"
keys[3] = "ac"
keys[4] = "ba"
keys[5] = "bb"
keys[6] = "bc"
keys[7] = "ca"
keys[8] = "cb"
keys[9] = "cc"

我可以在一个语句和/或一行中做同样的事情吗?

最佳答案

是的,您可以使用单个语句创建 map (在规范中称为 composite literal):

var keys = map[int]string{
    1: "aa",
    2: "ab",
    3: "ac",
    4: "ba",
    5: "bb",
    6: "bc",
    7: "ca",
    8: "cb",
    9: "cc",
}

或者,如果你在函数内部,你可以使用 short variable declaration :

keys := map[int]string{
    1: "aa",
    2: "ab",
    3: "ac",
    4: "ba",
    5: "bb",
    6: "bc",
    7: "ca",
    8: "cb",
    9: "cc",
}

关于dictionary - 在单个语句中初始化 Go map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078272/

相关文章:

angular - ionic 错误地理定位 ionic 未捕获( promise ): TypeError: Object(…) is not a function TypeError: Object(…) is not a function

c++ - 使用multimap c++​​打印邻接表

python - Python 是如何实现字典的?

c++ - 使用指针访问私有(private)数据成员

ruby - Go 加密不同于使用相同 key 和 iv 的 Ruby 加密

c - 使用 NULL 或 0 初始化变量和指针之间有区别吗?

c++ - 带有指针构造函数的指针

go - golang 中的 http HandleFunc 参数

go - 在C函数中更改golang C.String变量的值

ruby-on-rails - Stripe Live 可发布 API key 不正确