Making Decisions with if and else
Programs that choose their own path
So far your programs run the same steps every time. Real programs react: show this page if the user is logged in, warn if the password is too short. In Go, decisions are made with if.
The shape of an if
score := 75
if score >= 50 {
fmt.Println("You passed!")
}The condition score >= 50 is a question with a true or false answer. If it is true, the steps inside the braces run. If not, Go skips them. Two style notes that surprise people coming from other languages:
- No parentheses around the condition. Go likes it bare.
- The braces
{ }are always required, even for a single line.
else and else if
score := 91
if score >= 90 {
fmt.Println("Amazing!")
} else if score >= 50 {
fmt.Println("Nice work, you passed.")
} else {
fmt.Println("Keep practicing, you will get there.")
}Go checks the conditions from top to bottom and runs the first branch whose condition is true, then skips the rest. The final else is the catch-all when nothing above matched.
The comparison operators
==equal to, and!=not equal to<and>less than and greater than<=and>=less than or equal, greater than or equal
One = assigns a value, two == compare values. Writing if score = 50 is a compile error in Go, so the compiler catches this classic beginner slip for you.
Combining questions
You can join conditions with && (and), || (or), and flip one with ! (not):
age := 13
hasTicket := true
if age >= 12 && hasTicket {
fmt.Println("Welcome aboard!")
}With && both sides must be true. With || at least one side must be true.
A handy Go trick: if with a setup step
Go lets you do a small setup right inside the if, separated by a semicolon:
if total := 6 * 7; total > 40 {
fmt.Println("Big total:", total)
}Here total is created just for this if and its branches. You will see this pattern all over real Go code, especially for handling errors later.
Quick check
Q1 Which of these is required around the body of a Go if statement?
Q2 In an if / else if / else chain, which branch runs?
Want to save your progress? It's free.
Create a free account