Chapter 36: Nested if

Nested if means an if statement inside another if statement (or inside else / else if blocks). In Go this is perfectly legal, very common, but also very easy to get wrong — so we need to talk about it carefully.

Many beginners write deeply nested ifs at first, then after a few weeks/months they learn the Go community strongly prefers flat code (early returns + guard clauses) instead of deep nesting.

So today I want to show you both worlds:

  • how nested if works (syntax + mechanics)
  • real examples (good and bad)
  • why deep nesting is usually considered bad style in Go
  • the idiomatic alternatives most experienced Go developers use in 2025–2026

1. Basic Syntax of Nested if

Go

Important rules (same as normal if):

  • braces {} always required
  • no parentheses around conditions
  • you can nest as deep as you want (but please don’t go deeper than 3–4 levels)

2. Simple Nested Example – Temperature + Rain Check

Go

Output when temperature=38, isRaining=false:

text

3. Classic Bad Example – Deep Nesting (What Beginners Often Write)

Go

Problems with this style:

  • Hard to read (code moves far right)
  • Hard to test / debug
  • Easy to miss cases
  • Difficult to add new conditions later

4. Idiomatic Go Way – Flat Style with Early Returns (Guard Clauses)

This is what most experienced Go developers prefer in 2025–2026:

Go

Advantages of this style:

  • Code stays on the left margin (happy path is easy to see)
  • Each condition is independent and easy to test
  • Adding / removing checks is trivial
  • Much easier to read & maintain
  • Matches Go proverb: “Clear is better than clever”

5. When Nested if is Still Okay (Small & Shallow)

Small nested ifs are fine and common when:

  • the nesting level is only 2
  • the logic is very closely related
  • early return would make code less readable

Example (still acceptable):

Go

6. Your Quick Practice – Try Both Styles

Task: Write code that checks:

  • user not nil
  • user age >= 18
  • user has ticket
  • event is not cancelled

Print different messages.

First write it with deep nesting, then rewrite it with early returns.

Which version do you find easier to read?

Any part still confusing?

  • Why Go forces {} braces even for single statements?
  • How many levels of nesting is “too many”?
  • When to choose if-else chain vs switch vs early returns?
  • Or ready to move to switch statement next?

Keep experimenting with both styles — most Go developers start with nested if and gradually move to flat/early-return style as they read more real 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 *