How to Use an if Statement in Go
Programs make decisions: warn when it's hot, stop when an order isn't paid. Go's if runs its block only when the condition is true, and else if and else handle the other cases. Go has no brackets around the condition, and the braces are always required.
Syntax
if <condition> {
// runs when the condition is true
} else if <otherCondition> {
// runs when the first is false and this one is true
} else {
// runs when none were true
}
| Part | What it does |
|---|---|
if <condition> | Tests a bool condition, with no brackets around it. |
{ ... } | Required, even for one statement. |
} else if and } else | Must start on the same line as the closing brace. |
The Go specification says if statements "specify the conditional execution of two branches according to the value of a boolean expression."
The Example
The example describes the weather from a temperature: hot above 30, warm above 20, cool otherwise. The temperature is 24.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Code
Create a file named main.go:

package main
import "fmt"
func main() {
temperature := 24
if temperature > 30 {
fmt.Println("It is hot.")
} else if temperature > 20 {
fmt.Println("It is warm.")
} else {
fmt.Println("It is cool.")
}
}
Step 2: Run It
go run main.go
It is warm.

24 > 30 was false, so Go moved on; 24 > 20 was true, so it printed It is warm. and skipped the else. The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Writing = instead of ==, as in if t = 30 | syntax error: cannot use assignment t = 30 as value | Use == to compare |
Using a number as the condition, as in if 1 | non-boolean condition in if statement | Compare it: if n != 0 |
Starting else on its own line | syntax error: unexpected keyword else, expected } | Write } else { on one line |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
unexpected keyword else | else begins a new line | Join it to the closing brace |
| A branch you expected never runs | A condition above it already matched | Put the narrowest condition first |
FAQ
Can I run a statement before the condition?
Yes: if n, err := strconv.Atoi(s); err == nil { ... } runs the call first, and n and err exist only inside the if.
Is there a switch statement?
Yes. switch compares one value against several cases, without needing break.
Conclusion
Go's if takes a bool condition without brackets, always needs braces, and puts else on the line of the closing brace. else if and else cover the other cases.
Additional Resources
- If statements, in the Go specification.
- A Tour of Go: If.
