Short-statement if
Go's if can do something no if in C or Java can: declare a small variable right before the condition, and test that variable in the same line. The variable is only visible inside the if block and any else branches, which keeps the surrounding scope uncluttered.
n := 10
if rem := n % 2; rem == 0 {
fmt.Println(n, "is even (remainder", rem, ")")
} else {
fmt.Println(n, "is odd (remainder", rem, ")")
}
// rem is out of scope here
The shape is if shortStatement; condition { ... }. A semicolon separates the two parts. rem exists for the duration of the if/else block and disappears the moment you leave it.
if rem := n % 2; rem == 0 {
fmt.Println("even")
}
fmt.Println(rem) // compile error: undefined: rem
That short scope is the point. You keep the temporary value exactly where it is useful, and nowhere else.
Why this form is everywhere in real Go
This is how idiomatic Go handles "compute something, then check the result" without leaving the intermediate value hanging around afterwards. The most common use case by far is error handling:
if err := doSomething(); err != nil {
// handle err
return
}
// err is out of scope here
The error type and the doSomething() error pattern get their own chapter later in the course. The short-statement if is the standard way of writing error checks in Go, and you will see it in nearly every real Go program.
Scope covers both if and else
The variable declared in the short statement is visible in the if body, every else if, and the final else. It disappears once you leave the chain:
if sum := a + b; sum > 100 {
fmt.Println("big:", sum)
} else if sum > 50 {
fmt.Println("medium:", sum)
} else {
fmt.Println("small:", sum)
}
// sum is out of scope here
One variable, accessible everywhere you need it inside the chain, and cleaned up the instant the chain ends.
The short statement uses :=, which declares a new variable. If an outer scope already has a variable with the same name, the new one shadows it. The outer variable still exists and is unchanged, but every reference inside the if talks to the inner one:
rem := 99
if rem := 10 % 2; rem == 0 {
fmt.Println("inner rem:", rem) // 0
}
fmt.Println("outer rem:", rem) // still 99, not 0
Try this out in the starter: add a rem := 99 before your if, print rem inside and outside the block, and observe that the two prints disagree. Accidental shadowing is a real bug source in Go code, so give the inner variable a different name when you can, or use a plain if without the short statement.
The starter declares n := 42. Use the short-statement if to:
- Compute
n % 3into a variable calledremright inside theif. - In the
ifbranch, print"divisible by 3"whenremis0. - In the
elsebranch, print"remainder:"followed byrem.
rem should only be visible inside the if/else; do not declare it at function scope.
divisible by 3