Scooter
Scooter

Reputation: 7061

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

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 ) ] .

Upvotes: 3

Views: 175

Answers (1)

VonC
VonC

Reputation: 1323115

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.

Upvotes: 3

Related Questions