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?
- Limited Scope: The variable (like
lengthabove) is only defined within theifandelseblocks. It cannot be accessed elsewhere in the function, which prevents accidental reuse. - Conciseness: It combines declaration and logic into a single line.