Chapter 16: Boolean

1. What is the Boolean Type in Go?

  • Name: bool
  • Possible values: exactly two — true or false
  • Zero value (default when not initialized): false
  • Size in memory: usually 1 byte (implementation detail — not guaranteed, but true in all current Go implementations)
  • Category: predeclared / basic / primitive type
  • Case-sensitive: true and false must be lowercase — True or TRUE will not compile

2. How to Declare & Use Boolean Variables

Go gives you the same two styles as other variables:

Go

3. Where Booleans Come From in Real Code

Booleans are rarely hard-coded as true / false literals very often after the first examples.

They usually come from:

  • Comparison operators
  • Logical operators
  • Function returns
  • Map lookups (ok idiom)
  • Type assertions / type switches
  • Interface nil checks

a) From comparisons (most common source)

Go

b) Logical operators (AND, OR, NOT)

Operator Meaning Example Result
&& AND a && b true only if both true
OR
! NOT !a reverses value
Go

c) The famous ok idiom (map lookup, type assertion, channel receive, etc.)

Go

d) From functions (very common pattern)

Go

4. Booleans in Control Structures (if, for, switch)

Booleans are the heart of decisions in Go.

Go

5. Common Beginner Mistakes with bool

Go

6. Interesting / Advanced Notes (Good to Know Early)

  • No truthy/falsy like JavaScript/Python — only true/false are boolean → if “hello” → compile error → if 1 → compile error → must be explicit: if len(s) > 0 or if ptr != nil
  • Short-circuit evaluation (both && and ||)
Go
  • bool is not an integer — cannot do bool + bool or bool * 3

7. Your Quick Practice Exercise (Try Right Now)

Create bool_practice.go:

Go

Run it → change age to 19, 15, etc. and see how the booleans change.

Any part still fuzzy?

  • Logical operator precedence?
  • Booleans with pointers / nil checks?
  • How bool works in structs / maps?
  • Or ready to move to numeric types in more depth? or slices next?

You’re doing really well — booleans are small but they control everything in programs. Keep asking, keep coding! 💻🇮🇳 Let’s go! 🚀

You may also like...

Leave a Reply

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