Go Reference ยท Keywords and Statements
The if statement
Reference for Go if: braces rule, else if chains, init statements scoped to the branches, the comma-ok idiom, error checks and what counts as a condition.
if runs a block when a boolean condition is true, with optional else if and else branches. Go keeps it small: the condition needs no parentheses, the braces are mandatory, and the condition must be a real bool. Numbers, strings and pointers are never "truthy" or "falsy".
An if can start with a short statement, most often a := declaration. The variables it declares exist only in the if, its else if and its else branches, which keeps scope tight.
if n > 0 { fmt.Println("positive") }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
if condition { ... } else if condition { ... } else { ... } if init; condition { ... }
| Part | Description |
|---|---|
init |
An optional simple statement (declaration with :=, assignment, function call, increment) followed by a semicolon. |
condition |
An expression of type bool (including named boolean types). |
| braces | Required, even for one statement. The opening brace must be on the same line as if. |
else |
Must follow the closing brace on the same line (} else {), otherwise the automatic semicolon insertion breaks it. |
Errors and edge cases:
non-boolean condition in if statement:if xwith anintdoes not compile. Writeif x != 0.if x = 5 {is a syntax error; assignment is a statement, not an expression, so the=/==mix-up cannot silently compile.- Variables declared in the init statement are redeclared (shadowed) in each branch only if you use
:=again there.
Usage notes
- Early returns beat deep nesting. Idiomatic Go handles errors first and keeps the main path unindented:
if err != nil { return err }, then continue. - Avoid
elseafter areturn: the lint rule "indent error flow" flagsif cond { return x } else { ... }; drop theelse. - Short-circuit evaluation:
&&and||stop as soon as the result is known, soif p != nil && p.okis safe. - Comma-ok forms (
v, ok := m[k],v, ok := x.(T),v, ok := <-ch) are most often used in anifinit. - Scope pitfall:
if v, err := f(); err != nil {...}hides any outererr. See:=. - No ternary operator: Go has no
cond ? a : b; use anifstatement or a small helper function. For ordered choices with many branches, preferswitch. - Conditions are not evaluated twice: the init statement runs once, then the condition is tested.