Golang中的map字面量是一个bug还是有意为之的特性?

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

Golang bug or intended feature on map literals?

问题

刚开始学习Go语言,我需要一个字符串到字符串的映射,我希望能够直接初始化。

mapa := map[string]string{
        "jedan":"one",
        "dva":"two",
}

但是编译器报错了,提示syntax error: need trailing comma before newline in composite literal(复合字面量之前需要逗号或换行符)。

所以我不得不在"two",后面加上逗号,或者删除换行符,在最后一个值后面加上},编译器才能通过。

这是代码风格的预期行为吗?

编辑:为了明确起见,以下代码可以编译并正常工作:

mapa := map[string]string{
        "jedan":"one",
        "dva":"two",
}

go version go1.4.2 darwin/amd64 Mac OSX 10.9.5

英文:

Just started to learn Go and I need map of string string, that I initialize literally.

mapa := map[string]string{
        "jedan":"one",
        "dva":"two"
       }

But compiler is complaining syntax error: need trailing comma before newline in composite literal

So I had to add coma after "two", or delete a new line and have } after last value for compiler to be happy

Is this intended behavior of code style?

EDIT: to be clear follwing will compile and work

mapa := map[string]string{
        "jedan":"one",
        "dva":"two"  }

go version go1.4.2 darwin/amd64 Mac OSX 10.9.5

答案1

得分: 48

Go语言中有分号,但你看不到它们,因为它们是由词法分析器自动插入的。

分号插入规则如下:

  • 如果一行的最后一个标记是整数、浮点数、虚数、符文或字符串字面量,则自动在标记流的末尾插入一个分号。

因此,这段代码:

mapa := map[string]string{
    "jedan": "one",
    "dva":   "two"
}

实际上是这样的:

mapa := map[string]string{
    "jedan": "one",
    "dva":   "two";  // <- 分号
}

这是无效的Go代码。

英文:

Go has semicolons, but you don't see them because they're inserted automatically by the lexer.

Semicolon insertion rules:

> a semicolon is automatically inserted into the token stream at the end of a non-blank line if the line's final token is
>
> * an integer, floating-point, imaginary, rune, or string literal

So this:

mapa := map[string]string{
    &quot;jedan&quot;: &quot;one&quot;,
    &quot;dva&quot;:   &quot;two&quot;
}

is actually:

mapa := map[string]string{
    &quot;jedan&quot;: &quot;one&quot;,
    &quot;dva&quot;:   &quot;two&quot;;  // &lt;- semicolon
}

Which is invalid Go.

答案2

得分: 16

是的,是这样的。你应该选择添加逗号。

这样编辑地图/切片文字会更简单:你可以复制粘贴,移动项目,而不必担心最后一个项目后面不应该有逗号。

实际上,在PHP、JavaScript和许多其他语言中也可以这样做。

英文:

Yes it is. And you should choose the added comma.

It is much more simple to edit map/slice literals that way : you can copy-paster, move items around without worrying about the fact that the last item shouldn't be followed by a comma.

In fact, you can also do the same in PHP, javascript, and many other languages.

huangapple
  • 本文由 发表于 2015年3月27日 20:24:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/29300607.html
匿名

发表评论

匿名网友

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

确定