Chapter 28: Comparison

Comparison operators — the operators you use to make decisions, check conditions, sort things, validate input, filter data, etc.

In almost every real Go program (web handlers, CLI tools, data processing, games, APIs…), comparison operators appear many times per function.

Go’s comparison operators are very clean, very strict, very predictable — no weird JavaScript type coercion, no Python chaining surprises.

Let’s go through everything about comparison in Go like a patient human teacher would explain it — slowly, with many examples you can copy-paste and run right now.

1. The Six Comparison Operators in Go

Operator Meaning Works on types Example Result Important notes
== equal to almost all types (numbers, bool, string, array, struct, pointer, etc.) 5 == 5 “hi” == “hi” true byte-by-byte for strings
!= not equal to same as == 3 != 4 true != false true
< less than numbers, strings 10 < 20 “apple” < “banana” true lexicographical for strings
<= less than or equal numbers, strings 5 <= 5 true
> greater than numbers, strings 100 > 50 true
>= greater than or equal numbers, strings 0 >= -1 true

Very important Go rules:

  • Comparison operators do NOT chain like in Python → 10 < x < 20 → compile error
  • You cannot compare different types without explicit conversion → 5 == 5.0 → compile error (int vs float64)
  • Strings are compared byte by byte (lexicographical order based on UTF-8 byte values)

2. Runnable Examples — Copy-Paste & Run These

Create comparison_operators.go:

Go

3. Very Important Gotchas & Rules

  1. No automatic type conversion in comparisons
Go
  1. No chaining of comparisons
Go
  1. String comparison is case-sensitive and byte-based
Go
  1. Floating-point comparison is exact (dangerous!)
Go

Never use == for floats unless you really know what you’re doing. Use small epsilon instead:

Go

4. Real-World Patterns You Will Use Every Day

Go

5. Quick Practice – Try These Mentally or Run Them

Predict the result:

  1. “telangana” < “Telangana” → ?
  2. 25 == 25.0 → ?
  3. -5 < 0 → ?
  4. true == false → ?
  5. “హైదరాబాద్” == “Hyderabad” → ?

(Answers: false, compile error, true, false, false)

Any part still fuzzy?

  • Why no <=> three-way comparison like some languages?
  • How string comparison really works with Unicode/emoji?
  • Floating-point equality strategies?
  • Or ready for logical operators (&&, ||, !) next?

Keep typing small comparison expressions and printing results — these operators control almost every if, for, switch, sort, filter, validation in your future code.

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

You may also like...

Leave a Reply

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