Skip to content

Latest commit

 

History

History
59 lines (37 loc) · 3.19 KB

05.Semicolons.md

File metadata and controls

59 lines (37 loc) · 3.19 KB

Semicolons

Like C, Go's formal grammar uses semicolons to terminate statements, but unlike in C, those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them.

和 C 语言一样,Go 的正式语法使用分号作为语句的结束,但与 C 不同的是,这些分号不需要出现在源码中。而是由词法分析器在扫描源码时,根据一条简单的规则自动地插入,从而解放输入。

The rule is this. If the last token before a newline is an identifier (which includes words like int and float64), a basic literal such as a number or string constant, or one of the tokens

规则如下:如果新行之前的最后一个符号是一个标识符(像 int、float64 这样的词),基本的字面常量(如 number、string),或者如下符号之一

break continue fallthrough return ++ -- ) }

the lexer always inserts a semicolon after the token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”.

词法分析器总是会在这些符号后面插入一个分号。一言以蔽之:“如果新行之前的符号可以结束一条语句,那么久插入一个分号”。

A semicolon can also be omitted immediately before a closing brace, so a statement such as

紧邻右大括号之前的分号可以省略,所以下面一条语句不需要分号。

go func() { for { dst <- <-src } }()

needs no semicolons. Idiomatic Go programs have semicolons only in places such as for loop clauses, to separate the initializer, condition, and continuation elements. They are also necessary to separate multiple statements on a line, should you write code that way.

地道的 Go 程序仅在 for 循环中使用分号,用于分隔初始化,条件,continuation 等元素。分号也用于分隔一行中的多个语句,如果你非要那样写的话。

译注:此句“They are also necessary to separate multiple statements on a line, should you write code that way.”为虚拟语气,指将来可能发生的情况,这里的条件句“should you write code that way”放在了主句之后,且省略了连词,并使用了倒装,不易理解;改写一下的话,大致相当于:

Suppose you should write code in the way of putting multiple statements on a line, the semicolons are also necessary here.

但是这个主句中没有情态动词,不知是我理解有误还是原文句法本身不够标准。

One consequence of the semicolon insertion rules is that you cannot put the opening brace of a control structure (if, for, switch, or select) on the next line. If you do, a semicolon will be inserted before the brace, which could cause unwanted effects. Write them like this

分号插入规则的一个后果就是,你不能把控制语句(if, for, switch, or select)的左大括号放到新行上。如果你那样做,左大括号之前会被插入一个分号,这将导致编译错误,比如你应该这样写

if i < f() {
    g()
}

not like this

而不是这样写

if i < f()  // wrong!
{           // wrong!
    g()
}