Use condition initializers
Use condition initializers
Go allows a simple statement before an if condition, separated by a semicolon: if value := expression; condition { ... }. It runs once before the condition. A short declaration there creates a variable scoped to the entire if statement, including its else branches.
package main
import "fmt"
func main() { price, budget := 12, 20 if remaining := budget - price; remaining >= 0 { fmt.Println("left:", remaining) } else { fmt.Println("short:", -remaining) }}The initializer calculates the remainder before testing it. Both branches can use remaining, but code after the if cannot refer to this local declaration. Use this form when the computed value belongs only to the decision.
Avoid accidental shadowing
package main
import "fmt"
func main() { limit := 10 if limit := 3; limit < 5 { fmt.Println("inside:", limit) } fmt.Println("outside:", limit)}The inner := creates a different variable. It does not update the outer limit. If a value must remain available after the condition, declare it before the if. Do not confuse an initializer with assignment inside a Boolean expression; assignment is a statement in Go.
Try it locally
Use stock := 8 and requested := 11. Declare shortage in the if initializer as requested - stock. Print shortage: 3 if positive, otherwise print enough.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Branching 02: Use condition initializers
Check the lesson objective before moving on.
Where can a variable declared in an if initializer be used?
What is printed outside in the second program?