Skip to main content

How to Use an if Statement in Go

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

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
}
PartWhat it does
if <condition>Tests a bool condition, with no brackets around it.
{ ... }Required, even for one statement.
} else if and } elseMust 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 run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which sets temperature to 24 and prints It is hot. when it is above 30, It is warm. when it is above 20, and It is cool. otherwise.

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​

Terminal
go run main.go
Output
It is warm.

A zsh terminal where go run main.go prints 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​

MistakeWhat happensDo this instead
Writing = instead of ==, as in if t = 30syntax error: cannot use assignment t = 30 as valueUse == to compare
Using a number as the condition, as in if 1non-boolean condition in if statementCompare it: if n != 0
Starting else on its own linesyntax error: unexpected keyword else, expected }Write } else { on one line

Troubleshooting​

SymptomLikely causeFix
unexpected keyword elseelse begins a new lineJoin it to the closing brace
A branch you expected never runsA condition above it already matchedPut 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​