Chapter 29: Logical

Logical operators — the operators you use to combine conditions, make complex decisions, guard against nil pointers, check multiple requirements at once, etc.

Logical operators are extremely common in real Go code — almost every non-trivial if, for, switch, validation logic, filter, permission check, etc. uses them.

Go keeps logical operators very simple:

  • Only three logical operators exist
  • They work only on bool values
  • They have short-circuit evaluation (very important safety feature)
  • No compound assignment versions (&&=, ||=) — intentional design choice

Let’s go through them slowly and carefully, like we’re sitting together with VS Code open, writing small examples and printing results.

1. The Three Logical Operators in Go

Operator Name Meaning Example expression Result when… Short-circuits?
&& Logical AND true only if both operands are true a && b a = true AND b = true Yes
Logical OR true if at least one is true `a
! Logical NOT reverses the value !a !true = false, !false = true No

2. Truth Table (Quick Reference)

| A | B | A && B | A || B | !A | |——-|——-|——–|——–|——-| | true | true | true | true | false | | true | false | false | true | false | | false | true | false | true | true | | false | false | false | false | true |

3. Runnable Examples — Copy-Paste & Run These

Create logical_operators.go:

Go

4. The Most Important Feature: Short-Circuit Evaluation

This is why Go programmers love && and ||:

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

Real-world safety patterns you will use every day:

Go

Without short-circuit, the second part would be evaluated even when the first is false → panic or wrong result.

5. Precedence & Parentheses

  • && has higher precedence than ||
  • Always use parentheses when mixing them — makes code much clearer
Go

6. Common Beginner Mistakes

  1. Expecting Python-style chaining
Go
  1. Writing if !isError == true instead of if !isError
Go
  1. Forgetting short-circuit when writing safe checks

7. Quick Practice – Try These

Predict the result:

  1. true && false → ?
  2. false || true && false → ?
  3. !false || false → ?
  4. ptr != nil && *ptr == 42 (ptr = nil) → crashes or not?
  5. “Hyderabad” != “” && len(“Hyderabad”) > 5 → ?

Run them in a small program — which one surprised you?

Any part still confusing?

  • Why no &&= / ||= compound assignment?
  • How short-circuit interacts with function calls that have side effects?
  • Logical operators with non-bool types (spoiler: not allowed)?
  • Or ready for bitwise operators next?

Keep writing small if conditions with different combinations — logical operators control the flow of almost every interesting program you’ll write.

You’re doing really great — keep the momentum! 💪🇮🇳🚀

You may also like...

Leave a Reply

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