go if/for/func block open brace position required to be on the same line?

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

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.

huangapple
  • 本文由 发表于 2012年7月23日 14:28:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/11607425.html
匿名

发表评论

匿名网友

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

确定