Go Conditions
Conditions let a Go program branch its logic and run different code depending on whether an expression is true or false.
The if statement
Go keeps its conditional syntax deliberately spare. There are no parentheses required around the condition, but the opening brace of the block must sit on the same line as the condition itself. This is not a style preference — the Go compiler enforces it through automatic semicolon insertion, so writing the brace on its own line is a compile error.
Basic if statement
package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
}
}else and else if
An if statement can be extended with else to handle the case where the condition is false, and with one or more else if clauses to test additional conditions in sequence. Go evaluates each condition top to bottom and stops at the first one that is true.
if / else if / else chain
package main
import "fmt"
func main() {
score := 72
if score >= 90 {
fmt.Println("Grade: A")
} else if score >= 75 {
fmt.Println("Grade: B")
} else if score >= 60 {
fmt.Println("Grade: C")
} else {
fmt.Println("Grade: F")
}
}The init statement
A distinctive feature of Go's if is the optional short init statement, written before the condition and separated from it by a semicolon. Any variable declared there is scoped only to the if block and its else branches, which keeps helper variables from leaking into the surrounding function.
if with a short init statement
package main
import (
"fmt"
"strconv"
)
func main() {
if n, err := strconv.Atoi("42"); err == nil {
fmt.Println("Parsed number:", n)
} else {
fmt.Println("Conversion failed:", err)
}
}Boolean expressions, not truthy values
Unlike some languages, Go does not treat integers or strings as implicitly true or false. The condition in an if statement must be a genuine bool expression, so comparisons like x != 0 or checks like len(s) > 0 have to be written out explicitly.
- Comparison operators ==, !=, <, <=, >, >= all produce a bool.
- Logical operators && (and), || (or), and ! (not) combine boolean expressions.
- && and || short-circuit: the right-hand operand is not evaluated if the left side already determines the result.
- There is no ternary operator in Go — an if/else or a small helper function fills that role.
Exercise: Go Conditions
Do Go if statements require parentheses around the condition?