在Go语言中,如何编写多行语句?

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

In Go, how to write a multi-line statement?

问题

在Go语言中,我们可以使用反斜杠来表示当前语句继续到下一行。

例如,

a := b + c + s \
    + x + y

或者简单地,

a := b + c + s +
    x + y

在Go语言中也可以这样做。谢谢。

英文:

In python, we use backslash to indicate that the current statement continues to next line

for example,

a = b + c + s \
    + x + y

or simply,

a = b + c + s +
    x + y

Is it possible to do that in Go language? Thanks

答案1

得分: 87

当然可以,只需要在末尾加上一个运算符,例如:

a = b + c + s +
    x + y

还要注意的是,在运算符之前不能换行。以下代码是无效的:

a = b + c + s
    + x + y

该规则在这里规范中有描述。

英文:

Sure it is, just put an operator at the end, for example:

a = b + c + s +
    x + y

Also note that it's not possible to break the line before the operator. The following code is invalid:

a = b + c + s
    + x + y

The rule is described here and in the specification.

答案2

得分: 17

有趣的是,Go语言规范本身要求在每个语句的末尾加上分号,但是词法分析器会在编译之前在看起来像语句的行的末尾插入隐式分号。

因此,为了防止在未完成的行的末尾出现不需要的分号,你只需要确保该行不以可能使其看起来像一个完整语句的内容结尾。

换句话说,避免在不完整的行以变量、常量、函数、关键字或后缀操作符(例如++)结尾。

那还剩下什么呢?嗯,有几个东西可以考虑——中缀操作符(例如=+)、逗号或者开括号、花括号或者方括号。

英文:

Interestingly, the the Go language specification itself requires semicolons at the end of each statement, but the lexer will insert implicit semicolons at the end of lines that look like statements immediately before compilation.

Therefore, to prevent the unwanted semicolon at the end of an unfinished line, all you need to do is ensure that the line doesn't end with something that could make it look like a complete statement.

In other words, avoid ending an incomplete line in a variable, constant, function, keyword, or postfix operator (e.g. ++).

What does that leave? Well, a few things come to mind -- an infix operator (e.g. = or +), a comma, or an opening paren or brace or bracket, for example.

huangapple
  • 本文由 发表于 2011年6月24日 04:48:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/6460425.html
匿名

发表评论

匿名网友

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

确定