Chapter 32: Conditions

Conditions” or “Conditional Statements in Go”, they almost always mean:

How to make decisions in code — i.e. if, else if, else and especially Go’s very beloved if with initialization pattern

Go has no ternary operator (condition ? trueExpr : falseExpr), no Elvis operator, no switch expressions, no do-while, and no chained comparisons like 10 < x < 20.

So the if statement does almost all the decision-making work in Go — and it’s surprisingly elegant and powerful.

Let’s go through it step by step like we’re sitting together with VS Code open, writing small programs and running them live.

1. Basic if / else / else if – Syntax & Style Rules

Go

Important Go style rules (2025–2026 community standard):

  • Always use braces {} — even for one line → if x > 0 { return x } → never write if x > 0 return x
  • No parentheses around the condition → if x > 0 { ← correct → if (x > 0) { ← legal but not idiomatic
  • Prefer early returns over deep nesting → “happy path” stays on the left side

2. The Most Loved Go Feature: if with Initialization

This pattern is everywhere in real Go code.

You can declare one or more variables right inside the if statement — they are only visible inside that if/else block.

Go

Why everyone loves this pattern:

  • Variable lives only as long as needed
  • No unnecessary variables hanging around in outer scope
  • Very clean error handling idiom: if err != nil { return … }

3. Conditions with Logical & Comparison Operators

Go

Short-circuit evaluation (extremely important):

  • && stops as soon as it finds false
  • || stops as soon as it finds true

→ This prevents crashes in the example above

4. Idiomatic Patterns You Will Use Every Day

Pattern 1: Guard clauses / early returns

Go

Pattern 2: Input / parameter validation

Go

Pattern 3: Range checking

Go

5. Quick Practice – Try Writing These

  1. Write an if chain that classifies temperature:
    • < 0 → “Freezing ❄️”
    • 0–15 → “Cold 🥶”
    • 16–25 → “Pleasant 🌤️”
    • 26–35 → “Warm ☀️”
    • 35 → “Hot 🔥”

  2. Write a safe check: if a map key exists and its value > 100, print “High value”
  3. Write a function that returns early if input is invalid

Which style felt most comfortable — normal if-else or if-with-init?

Any part still unclear?

  • Why no ternary operator in Go philosophy?
  • How deep is too deep for if nesting?
  • Short-circuit behavior with expensive function calls?
  • Or ready to move to switch statement next?

Keep writing small if conditions — they are the heart of almost every meaningful decision in your future programs.

You’re doing fantastic — keep asking! 💪🇮🇳🚀

You may also like...

Leave a Reply

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