The Initial Statement

An if conditional in Go can include an “initial” statement that runs before the condition is evaluated. This is a powerful feature for keeping your code clean.

Syntax

The initial statement is separated from the condition by a semicolon ;.

if INITIAL_STATEMENT; CONDITION {
    // block
}

Example

Instead of declaring a variable in the outer scope, you can localize it:

// Instead of this:
length := getLength(email)
if length < 10 {
    fmt.Printf("Email is too short: %d\n", length)
}

// Do this:
if length := getLength(email); length < 10 {
    fmt.Printf("Email is too short: %d\n", length)
}

Why use it?

  1. Limited Scope: The variable (like length above) is only defined within the if and else blocks. It cannot be accessed elsewhere in the function, which prevents accidental reuse.
  2. Conciseness: It combines declaration and logic into a single line.