一次操作中声明具有键值对的映射。

huangapple go评论70阅读模式
英文:

declare map with key value pairs in one operation

问题

可以使用以下方式声明一个具有键值对的映射:

var env = map[string]int{
    "key0": 10,
    "key1": 398,
}

这样就创建了一个名为env的映射,其中包含两个键值对。键的类型为string,值的类型为int。键值对之间使用冒号分隔,每个键值对之间使用逗号分隔。

英文:

Is it possible to declare a map with key value pairs?

Something like this

var env map[string]int{
    "key0": 10,
    "key1": 398
}

答案1

得分: 4

是的,你可以使用键值对声明一个map。你可以使用变量声明和map的复合字面量:

var env = map[string]int{
   "key0": 10,
   "key1": 398,
}

或者使用短变量声明和复合字面量:

env := map[string]int{
   "key0": 10,
   "key1": 398,
}

短变量声明只能在函数内部使用,而变量声明可以在函数和包级别使用。

还要注意在398后面添加了逗号。

英文:

Yes, you can declare a map with name value pairs. You can use a variable declaration with a map composite literal:

var env = map[string]int{
   "key0": 10,
   "key1": 398,
}

or a short variable declaration with the composite literal:

env := map[string]int{
   "key0": 10,
   "key1": 398,
}

The short variable declaration can only be used in a function. The variable declaration can be used in functions and at package level.

Also note the added "," following the 398.

答案2

得分: 3

这是一个来自《Go maps in action》的例子:

commits := map[string]int{
    "rsc": 3711,
    "r":   2138,
    "gri": 1908,
    "adg": 912,
}

如果没有最后的逗号,会出现语法错误:

syntax error: need trailing comma before newline in composite literal

需要注意的是,从Go 1.5(2015年8月)开始,你可以在map字面量中使用字面量作为map的键(不仅仅是值)。
参考review 2591commit 7727dee

map[string]Point{"orig": {0, 0}}    // 等同于 map[string]Point{"orig": Point{0, 0}}
map[Point]string{{0, 0}: "orig"}    // 等同于 map[Point]string{Point{0, 0}: "orig"}
英文:

It is, but you need to add an extra ',' and, in your case, a = (var env = map...) .

Here is an example from "Go maps in action":

commits := map[string]int{
    "rsc": 3711,
    "r":   2138,
    "gri": 1908,
    "adg": 912,
}

Without the final ',', you get:

syntax error: need trailing comma before newline in composite literal

Note with Go 1.5 (August 2015), you will be able to use literal for map key (and not just for map values), in the case of a map literal.
See review 2591 and commit 7727dee.

map[string]Point{"orig": {0, 0}}    // same as map[string]Point{"orig": Point{0, 0}}
map[Point]string{{0, 0}: "orig"}    // same as map[Point]string{Point{0, 0}: "orig"}

huangapple
  • 本文由 发表于 2014年9月27日 06:14:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/26069057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定