Go If..Else
Conditional statements let your program choose between different paths. Go's if looks like other C-family languages, with two differences: no parentheses around the condition, and the braces are always required, even for a single statement.
if
package main
import "fmt"
func main() {
temperature := 31
if temperature > 30 {
fmt.Println("It's hot — drink some water.")
}
fmt.Println("Forecast done.")
}It's hot — drink some water.
Forecast done.
if … else
else runs when the condition is false. It must be on the same line as the closing } of the if block — otherwise automatic semicolon insertion breaks the statement.
package main
import "fmt"
func main() {
balance := 40
price := 55
if balance >= price {
fmt.Println("Purchase approved")
} else {
fmt.Println("Insufficient funds, missing", price-balance)
}
}Insufficient funds, missing 15
else if chains
Use else if to test several conditions in order. The first one that is true wins; the rest are skipped.
package main
import "fmt"
func grade(score int) string {
if score >= 90 {
return "A"
} else if score >= 80 {
return "B"
} else if score >= 70 {
return "C"
} else {
return "F"
}
}
func main() {
for _, s := range []int{95, 83, 71, 40} {
fmt.Println(s, "->", grade(s))
}
}95 -> A
83 -> B
71 -> C
40 -> F
if with a short statement
An if can begin with a short statement, separated from the condition by a semicolon. Variables declared there are only visible inside the if and its else branches. This is extremely common with functions that return an error.
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err != nil {
fmt.Println("not a number:", err)
} else {
fmt.Println("parsed", n, "doubled is", n*2)
}
if n, err := strconv.Atoi("forty"); err != nil {
fmt.Println("not a number:", err)
} else {
fmt.Println("parsed", n)
}
// n and err do not exist here
}parsed 42 doubled is 84
not a number: strconv.Atoi: parsing "forty": invalid syntax
Nested if
You can put an if inside another. But deep nesting gets hard to read quickly — Go programmers prefer early returns ("guard clauses") that handle the unusual case first and keep the main path un-indented.
package main
import "fmt"
// Nested version
func canRentNested(age int, hasLicense bool) string {
if age >= 21 {
if hasLicense {
return "yes"
} else {
return "no: license required"
}
} else {
return "no: too young"
}
}
// Early-return version: same logic, flatter
func canRent(age int, hasLicense bool) string {
if age < 21 {
return "no: too young"
}
if !hasLicense {
return "no: license required"
}
return "yes"
}
func main() {
fmt.Println(canRentNested(25, true), "|", canRent(25, true))
fmt.Println(canRentNested(25, false), "|", canRent(25, false))
fmt.Println(canRentNested(19, true), "|", canRent(19, true))
}yes | yes
no: license required | no: license required
no: too young | no: too young
Note: Go has no ternary operator (
cond ? a : b). Use a regularif/else, or assign a default first and override it in anif.
| Rule | Example |
|---|---|
| No parentheses needed | if x > 0 { |
| Braces always required | if ok { return } |
else on the same line as } |
} else { |
| Optional init statement | if v, ok := m[k]; ok { |
Common mistakes
A few errors trip up almost everyone coming from other languages:
- Putting
elseon its own line. The closing}followed by a newline ends the statement, soelseon the next line is a syntax error. Always write} else {. - Using
=instead of==. In Go, assignment is a statement, not an expression, soif x = 5 {does not compile — the compiler catches the typo for you. - Shadowing a variable in the init statement.
if err := f(); err != nil { ... }creates a newerrthat disappears after theif. If you need the value later, declare it before theif. - Writing
if found == true. It works, butif foundis shorter and idiomatic; likewiseif !foundinstead ofif found == false.
Test yourself
Which if is valid Go?
if (x > 5) fmt.Println(x)if x > 5 { fmt.Println(x) }if x > 5: fmt.Println(x)if x > 5 then fmt.Println(x)
Where is a variable declared in if v := f(); v > 0 { ... } visible?
- In the whole function
- Only in the
if,else ifandelseblocks - Only in the
ifblock - In the whole package
Does Go have a ternary operator like a > b ? a : b?
- Yes
- No
- Only for numbers
- Only in constants