英文:
Is go if/for/func block open brace position required to be on the same line?
问题
一个跟在for、func或if语句后面的go块是否必须在同一行上有开括号?如果我将它移到下一行,我会得到一个编译错误,但我在语言规范中找不到它们展示块必须按照那种结构的地方。
一个块是在匹配的大括号内的声明和语句的序列。
块 = "{" { 语句 ";" } "}"。
IfStmt = "if" [ 简单语句 ";" ] 表达式 块 [ "else" ( IfStmt |
块 ) ]。
英文:
Does a go block following a for, func or if statement have to have the opening brace on the same line? I get a compile error if I move it down but I can't see in the language spec where they show that a block has to be structured like that.
> A block is a sequence of declarations and statements within matching
> brace brackets.
>
> Block = "{" { Statement ";" } "}" .
>
> IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt |
> Block ) ] .
答案1
得分: 3
从Effective Go中,因为有分号推断:
> 有一个注意事项。
你永远不应该将控制结构(if,for,switch或select)的左大括号放在下一行。
如果你这样做,分号将会在左大括号之前插入,可能会导致意想不到的效果。应该像这样写:
if i < f() {
g()
}
> 而不是像这样写:
if i < f() // 错误!
{ // 错误!
g()
}
正如jnml所评论的,语言语法对于代码块是正确的。
但是结合 分号注入,这意味着你应该真正:
- 总是将左大括号放在与if语句相同的行上(否则'
if
'将不会按照你认为的方式执行) - 实际上,总是使用
gofmt
,不要考虑它(最好在编辑器中每次保存代码时都使用gofmt。它很快,会使你的代码与其他任何Go代码保持一致)
即使Go编译器也会强制执行“左大括号放在同一行”的规则,以避免任何意想不到的副作用。
因此,语言参考没有说明应该将左大括号放在哪里,但是gofmt
和编译器都会确保它在if
语句中正确放置。
英文:
From Effective Go, because of semicolon inference:
> One caveat.
You should never 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 i < f() {
g()
}
> not like this:
if i < f() // wrong!
{ // wrong!
g()
}
As jnml comments, the language syntax is correct for blocks.
But combined with Semicolon injection, it means you should really:
- always put the brace on the same line than the if statement (or the '
if
' won't do what you think it should) - actually, always use
gofmt
and don't think about it (Preferably, gofmt your code each time you save it in your editor. It is fast and will make your code consistent with the rest of any Go code out there)
Even the Go compiler will enforce that "same line for brace" rule, to avoid any unforeseen side-effect.
So the language reference doesn't say where to put the brace, but both gofmt
and the compiler will make sure it is correctly placed for a if
statement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论