为什么我在这里需要一个分号?

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

Why do I need a semicolon here?

问题

这是一个测试的Go程序:

package main
import fmt "fmt"
func main () {
    ex := "moo cow\n";
    fmt.Print (ex)
}

加上分号后,它可以编译通过。然而,如果移除分号,就无法通过编译:

string.go:5: 附近有语法错误 fmt

有什么想法吗?


更新(2012年3月):较新的Go版本可以编译这两种形式(带和不带分号)。

英文:

Here is a test Go program:

package main
import fmt "fmt"
func main () {
    ex := "moo cow\n";
    fmt.Print (ex)
}

With the semicolon, it compiles. However, if the semicolon is removed, it doesn't:
<pre>
string.go:5: syntax error near fmt
</pre>
Any ideas?


Update (March 2012): Newer Go releases are able to compile both forms (with and without the semicolon).

答案1

得分: 13

Go编程语言规范中:

> 语句列表的元素由分号分隔,只有在前一个语句:
>
> - 以声明列表的右括号“)”结尾;或者
> - 以不是表达式的右大括号“}”结尾,
>
> 分号才可以省略。

英文:

From The Go Programming Language Specification:

> Elements of a list of statements are
> separated by semicolons, which may be
> omitted only if the previous
> statement:
>
> - ends with the closing parenthesis ")" of a list of declarations; or
> - ends with a closing brace "}" that is not part of an expression.

答案2

得分: 2

好的,以下是翻译好的部分:

答案在这里:http://golang.org/doc/effective_go.html#semicolons,但是并不是很清楚。看起来你可以在语句的末尾省略分号,但是不能省略表达式的分号。我认为(在这里我不确定)表达式是任何包含“=”(或“:=”)的内容(尽管在教程中使用“+=”似乎也可以)。

英文:

Well, the answer's technically here: http://golang.org/doc/effective_go.html#semicolons, but it's not very clear. It looks like you can leave semicolons off the end of statements, but not expressions. I think (I'm not certain here) that expressions are anything with an "=" (or ":=") in them (although += seems to be fine in the tutorial?)

huangapple
  • 本文由 发表于 2009年11月12日 13:03:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/1719999.html
匿名

发表评论

匿名网友

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

确定