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 else clause in Go is a conditional control flow construct that dictates the execution of a specific block of code when the boolean expression of its associated if or else if statement evaluates to false.
if condition {
    // Executed if condition is true
} else {
    // Executed if condition is false
}

Lexical Constraints and Formatting

Go enforces strict formatting rules for the else clause. The else keyword must appear on the exact same line as the closing brace } of the preceding if block. If the else keyword is placed on a new line, Go’s lexer will apply its automatic semicolon insertion rule after the closing brace }, resulting in a compile-time syntax error (unexpected else, expecting }). Valid Syntax:
if x > 0 {
    x--
} else {
    x++
}
Invalid Syntax (Compile Error):
if x > 0 {
    x--
}
else {    // ERROR: unexpected else
    x++
}

Mandatory Braces

Unlike C, C++, or Java, Go does not permit the omission of curly braces {} for single-line statements. The else block must always be enclosed in braces, ensuring uniform block scoping and preventing dangling-else ambiguities.

Variable Scoping

Go allows an optional initialization statement to precede the boolean condition in an if statement. Any variables declared within this initialization statement are lexically scoped to the entire if-else chain. They are fully accessible within the else block.
if val := computeValue(); val > 10 {
    // val is accessible here
    fmt.Println("High:", val)
} else {
    // val remains in scope and is accessible here
    fmt.Println("Low:", val)
}
// val is out of scope here

Chaining with else if

To evaluate multiple, mutually exclusive conditions sequentially, the else clause can be immediately followed by another if statement. The same lexical rules apply: else if must remain on the same line as the preceding closing brace.
if conditionA {
    // Executed if conditionA is true
} else if conditionB {
    // Executed if conditionA is false AND conditionB is true
} else {
    // Executed if both conditionA and conditionB are false
}
Master Go with Deep Grasping Methodology!Learn More