Skip to main content
The Go if statement supports an optional initialization statement executed immediately before the condition is evaluated. This construct allows for the declaration and initialization of variables strictly within the lexical scope of the conditional block, preventing namespace pollution in the enclosing scope.

Syntax

The initialization statement is separated from the boolean condition by a semicolon (;).

Execution Mechanics

  1. Initialization: The initialization_statement (typically a short variable declaration :=, a simple assignment =, or a function call) is executed exactly once.
  2. Evaluation: The condition is evaluated. It must resolve to a typed or untyped boolean value.
  3. Branching: If the condition evaluates to true, the if block executes. If false, control flow proceeds to the else if or else blocks, if present.

Lexical Scoping and Lifetime

Variables declared within the initialization statement are block-scoped. Their lexical visibility is restricted to:
  • The body of the if block.
  • The condition and body of any attached else if blocks.
  • The body of any attached else block.
While the lexical scope of these variables is strictly confined to the if-else chain, their lifetime is determined by Go’s escape analysis and reachability rules. If a reference to the initialized variable (such as a pointer or a closure) escapes the block, the variable is allocated on the heap and will outlive the if statement.

else if Initialization

The else if branches can also declare their own initialization statements. This creates further nested implicit blocks. Variables declared in an else if initialization are scoped to that specific else if block and any subsequent else if or else blocks in the chain. They do not affect preceding blocks, but they do inherit visibility of variables declared in preceding if or else if initializations.

Variable Shadowing

Because the initialization statement creates a new lexical block, using the short variable declaration (:=) will shadow variables of the same name declared in the outer enclosing scope. To mutate an outer variable rather than shadowing it, the standard assignment operator (=) must be used instead of the short variable declaration.
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More