Semicolons
Most Go semicolons are inserted automatically; understanding the insertion rules explains several odd-looking syntax errors.
Canonical guidance
- the lexer inserts most semicolons automatically at line ends after specific token kinds
- this affects brace placement and line breaking
- explicit semicolons are rare outside special one-line forms
Use when
- explaining parse errors caused by newlines
- reviewing odd formatting around control flow
- understanding why Go requires certain brace placement
Avoid
- moving
{onto a new line afterif,for,switch, or function declarations - assuming a newline is always just whitespace
- writing code as though Go followed JavaScript or C semicolon habits
Preferred pattern
if ok {
use()
}
Anti-pattern
- putting the opening brace on the next line after a control statement
Explanation: This is tempting if you prefer another house style, but semicolon insertion changes the token stream and breaks the syntax.
Why
- semicolon insertion is a small rule with outsized impact on parser errors and formatting questions