else if Statement
Start with Go else if Statement
Use an else if chain when you have more than two mutually exclusive outcomes. Conditions are checked from top to bottom until one matches.
What you’ll learn
- Build a multi-way choice using else if.
- Explain short-circuiting of later branches.
- Order conditions to avoid incorrect matches.
Understand the idea
In Go, write else if as two words. The first true branch executes and the remaining conditions in the chain are not evaluated. An optional final else catches values that matched none of the earlier conditions.
The order of the conditions matters. Put narrow or high-priority cases before broad cases, or a broad condition may consume values that should match a later condition.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
score := 82
if score >= 90 {
fmt.Println("Grade A")
} else if score >= 75 {
fmt.Println("Grade B")
} else if score >= 50 {
fmt.Println("Grade C")
} else {
fmt.Println("Needs improvement")
}
}
Output
Grade BTrace what the program does
With 82, the first test (score >= 90) fails. The next test (score >= 75) succeeds, so the program prints Grade B and skips the rest. You never get multiple grades from this single chain.
Avoid common mistakes
- If the broad condition
score >= 50comes first, higher scores may be classified incorrectly. elseifis not a Go keyword; writeelse if.
Try it yourself
Test scores 95, 75, 49 and 50. State which branch each value enters before running the program.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go else if Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.