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

Go

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)

Go

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.

Go

Even more common real-world example (you’ll write this pattern daily):

Go

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):

Go

Better (flat & readable):

Go

5. Quick Practice – Try Writing These

  1. Create a chain that classifies age:
    • < 13 → “Child”
    • 13–19 → “Teenager”
    • 20–35 → “Young adult”
    • 36–60 → “Adult”
    • 60 → “Senior”

  2. Write an else if chain for a simple calculator result:
    • result > 100 → “Excellent”
    • result >= 75 → “Good”
    • result >= 50 → “Pass”
    • else → “Try again”
  3. 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! 💪🇮🇳🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *