Chapter 35: else if Statement
Else if — which in Go is not a separate keyword or special syntax, but simply the natural way to chain multiple conditions using else if.
In Go there is no dedicated “elseif” keyword (like in some other languages). Instead you just write else if — and because braces are always required, the structure stays very clean and readable.
Let me explain everything about else if chains in Go like we’re sitting together with VS Code open — slowly, with real examples, style notes, common patterns, mistakes to avoid, and why Go made this design choice.
1. Basic Syntax – How else if Actually Looks
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
if firstCondition { // ... } else if secondCondition { // ... } else if thirdCondition { // ... } else { // ... } |
Important rules (compiler enforces most of them):
- No parentheses around conditions (same as plain if)
- Braces {} are mandatory for every block — even single-line
- You can have as many else if clauses as you want (though >5–6 usually means you should refactor)
- The final else is optional
- Conditions are evaluated top to bottom — first true block runs, rest are skipped
2. Real Example – Temperature Classifier (very common beginner exercise)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package main import "fmt" func main() { temp := 37 // change this value and run again if temp >= 45 { fmt.Println("Dangerous heatwave — stay indoors!") } else if temp >= 40 { fmt.Println("Very hot — drink lots of water ☀️💧") } else if temp >= 35 { fmt.Println("Hot — avoid direct sunlight") } else if temp >= 30 { fmt.Println("Warm — pleasant Hyderabad weather") } else if temp >= 20 { fmt.Println("Comfortable — nice day for a walk") } else if temp >= 10 { fmt.Println("Cool — light jacket recommended") } else { fmt.Println("Cold — wear something warm 🧥") } } |
Run this, change temp to 42, 28, 12, -2, etc. — see how only one message appears.
3. The Most Important & Idiomatic Pattern: else if + Initialization
This is where Go really shines — you can use the short variable declaration in any of the if / else if conditions.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
score := 82 if grade, err := getGrade(score); err != nil { fmt.Println("Error calculating grade:", err) } else if grade == "A" { fmt.Println("Outstanding! 🎉") } else if grade == "B" { fmt.Println("Very good") } else if grade == "C" { fmt.Println("Good effort") } else if grade == "D" { fmt.Println("Needs improvement") } else { fmt.Println("Failed — let's work harder next time") } // 'grade' and 'err' are only visible inside this chain |
Even more common real-world example (you’ll write this pattern daily):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
value, err := strconv.Atoi(userInput) if err != nil { fmt.Println("Not a valid number:", err) } else if value < 0 { fmt.Println("Negative numbers not allowed") } else if value == 0 { fmt.Println("Zero is a special case") } else if value > 100 { fmt.Println("Value too large") } else { fmt.Println("Valid number:", value) } |
4. Style & Best Practices (What Experienced Go Developers Do)
- Keep chains short — if you have >4–5 else if, consider:
- switch statement
- map of handlers
- early returns + guard clauses
- separate function
- Prefer early returns over long else chains
Bad (deep nesting):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
if user != nil { if user.IsLoggedIn { if user.HasRole("admin") { // do admin stuff } } } |
Better (flat & readable):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if user == nil { return ErrNotAuthenticated } if !user.IsLoggedIn { return ErrNotLoggedIn } if !user.HasRole("admin") { return ErrForbidden } // happy path |
5. Quick Practice – Try Writing These
- Create a chain that classifies age:
- < 13 → “Child”
- 13–19 → “Teenager”
- 20–35 → “Young adult”
- 36–60 → “Adult”
-
60 → “Senior”
- Write an else if chain for a simple calculator result:
- result > 100 → “Excellent”
- result >= 75 → “Good”
- result >= 50 → “Pass”
- else → “Try again”
- Combine with initialization: check length of a string and give different messages
Which chain felt easiest to read?
Any part still confusing?
- Why Go forces {} braces even for one-liners?
- Why no ternary operator (?:) in Go?
- When to choose if-else vs switch?
- Or ready to move to switch statement next?
Keep writing these small if-else chains — they are literally the most used decision-making tool in real Go code.
You’re making fantastic progress — keep asking! 💪🇮🇳🚀
