The GoDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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
- Initialization: The
initialization_statement(typically a short variable declaration:=, a simple assignment=, or a function call) is executed exactly once. - Evaluation: The
conditionis evaluated. It must resolve to a typed or untyped boolean value. - Branching: If the condition evaluates to
true, theifblock executes. Iffalse, control flow proceeds to theelse iforelseblocks, 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
ifblock. - The condition and body of any attached
else ifblocks. - The body of any attached
elseblock.
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.
Master Go with Deep Grasping Methodology!Learn More





