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:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package main import "fmt" func main() { // Style 1: full var declaration (explicit) var isAdult bool = true var hasCoffee bool // ← no value → gets zero value false // Style 2: short declaration (most common & idiomatic) isLearningGo := true isTired := false // Print them nicely fmt.Printf("isAdult: %t (type: %T)\n", isAdult, isAdult) // isAdult: true (type: bool) fmt.Printf("hasCoffee: %t ← zero value!\n", hasCoffee) // hasCoffee: false ← zero value! fmt.Printf("isLearningGo: %t\n", isLearningGo) } |
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)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
age := 25 isAdult := age >= 18 // true isTeen := age >= 13 && age <= 19 // true isSenior := age >= 60 // false fmt.Println("Adult?", isAdult) // Adult? true |
b) Logical operators (AND, OR, NOT)
| Operator | Meaning | Example | Result |
|---|---|---|---|
| && | AND | a && b | true only if both true |
|
OR | ||
| ! | NOT | !a | reverses value |
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
hasTicket := true hasID := false canEnter := hasTicket && hasID // false canEnterOr := hasTicket || hasID // true cannotEnter := !canEnter // true fmt.Printf("Can enter? %t\n", canEnter) // false |
c) The famous ok idiom (map lookup, type assertion, channel receive, etc.)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
m := map[string]int{"apple": 5, "banana": 3} value, ok := m["orange"] // ok is bool — false if key missing if ok { fmt.Println("Found:", value) } else { fmt.Println("Not found → ok is", ok) // Not found → ok is false } |
d) From functions (very common pattern)
|
0 1 2 3 4 5 6 7 8 9 10 |
func isEven(n int) bool { return n%2 == 0 } fmt.Println("42 is even?", isEven(42)) // true |
4. Booleans in Control Structures (if, for, switch)
Booleans are the heart of decisions in Go.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
isRaining := true if isRaining { fmt.Println("Take umbrella ☔") } else { fmt.Println("Nice weather!") } // No parentheses needed around condition — clean! if !isRaining && temperature > 30 { fmt.Println("Go to Tank Bund!") } // for loop with bool condition (like while) attempts := 0 for attempts < 3 { // bool expression attempts++ fmt.Println("Trying...", attempts) } |
5. Common Beginner Mistakes with bool
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// ❌ Wrong — Go has no implicit conversion from int to bool if age { // compile error // ... } // ❌ Wrong — cannot use = for comparison if age = 18 { // assignment, not comparison — error // Correct if age == 18 { |
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 ||)
|
0 1 2 3 4 5 6 7 8 |
if ptr != nil && *ptr > 0 { // safe — if ptr is nil, second part not evaluated // ... } |
- bool is not an integer — cannot do bool + bool or bool * 3
7. Your Quick Practice Exercise (Try Right Now)
Create bool_practice.go:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package main import "fmt" func main() { age := 17 hasLicense := false hasParent := true // Write boolean expressions for these questions: canDriveAlone := age >= 18 && hasLicense canDriveWithParent := age >= 16 && hasParent isAllowed := canDriveAlone || canDriveWithParent fmt.Printf("Can drive alone? %t\n", canDriveAlone) fmt.Printf("Can drive with parent? %t\n", canDriveWithParent) fmt.Printf("Is allowed to drive? %t\n", isAllowed) // Bonus: negate fmt.Printf("Not allowed? %t\n", !isAllowed) } |
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! 🚀
