Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The if statement in Go is a control flow construct used for conditional execution of code blocks based on the evaluation of a boolean expression.
if condition {
    // execution block
}

Technical Characteristics

  • No Parentheses: The boolean condition does not require enclosing parentheses ().
  • Mandatory Braces: The execution block must be enclosed in curly braces {}. Single-line if statements without braces are syntactically invalid.
  • Brace Placement: Due to Go’s automatic semicolon insertion (ASI), the opening brace { must appear on the same line as the end of the condition. The condition itself may span multiple lines, but placing the opening brace on a new line after the condition’s conclusion will result in a compilation error.
  • Strict Boolean Evaluation: The condition must evaluate strictly to a bool type. Go does not support implicit type coercion or “truthiness” (e.g., integers like 1 or 0, empty strings, or non-nil pointers cannot be evaluated directly as boolean conditions).

Extended Syntax (else if and else)

Go supports branching via else if and else clauses.
if conditionA {
    // block A
} else if conditionB {
    // block B
} else {
    // default block
}
Formatting Constraint: The else if or else keywords must be placed on the same line as the closing brace } of the preceding block. Placing else on a new line triggers automatic semicolon insertion after the closing brace, resulting in a syntax error.

Initialization Statement

Go allows an optional initialization statement to be executed immediately before the boolean condition is evaluated. This is typically a short variable declaration.
if initialization_statement; condition {
    // execution block
}
Lexical Scoping Rules:
  1. Block Scope: Variables declared within the initialization statement are scoped exclusively to the if block, as well as any subsequent else if or else blocks in the same chain.
  2. Shadowing: Variables declared in the initialization statement will shadow variables of the same name existing in the outer lexical scope for the duration of the if chain.
  3. Scope Termination: Once execution exits the if-else chain, variables declared in the initialization statement go out of scope and are no longer accessible by name. (Note: Variable lifetime is determined separately by Go’s escape analysis, not strictly by this lexical scope).
Master Go with Deep Grasping Methodology!Learn More