In Go, how to write a multi-line statement?
In python, we use backslash to in开发者_JAVA技巧dicate 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
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.
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.
精彩评论