BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Boolean Types

Go 1.23

Booleans in Go are a distinct type `bool` with values `true` or `false`. This example covers logical operators (`&&`, `||`, `!`), short-circuit evaluation, and how booleans are used in control flow.

Code

package main

import "fmt"

func main() {
    // 1. Declaration
    // Booleans can only be true or false.
    // The zero value is false.
    var isActive bool   // false by default
    isValid := true     // inferred as bool

    fmt.Println("isActive:", isActive)
    fmt.Println("isValid:", isValid)

    // 2. Logical Operators
    // && (AND), || (OR), ! (NOT)
    a := true
    b := false

    fmt.Println("a && b:", a && b) // false
    fmt.Println("a || b:", a || b) // true
    fmt.Println("!a:", !a)         // false

    // 3. Short-Circuit Evaluation
    // Go evaluates the left side first. If the result is already determined,
    // the right side is NOT executed.
    
    // In (true || check()), check() is NEVER called.
    if true || expensiveCheck() {
        fmt.Println("Short-circuit OR: skipped expensive check")
    }

    // In (false && check()), check() is NEVER called.
    if false && expensiveCheck() {
        // Unreachable
    } else {
        fmt.Println("Short-circuit AND: skipped expensive check")
    }
}

func expensiveCheck() bool {
    fmt.Println("Running expensive check...")
    return true
}

Explanation

Go has a strict boolean type named bool. Unlike some languages (like C or JavaScript) where integers or other types can be treated as "truthy" or "falsy", Go requires an explicit boolean expression for conditions. For example, if 1 { ... } is a compile-time error; you must write if 1 == 1 { ... }.

Go supports the standard logical operators:

  • && (AND): Returns true only if both operands are true.
  • || (OR): Returns true if at least one operand is true.
  • ! (NOT): Inverses the boolean value.

A key feature is short-circuit evaluation. For &&, if the left operand is false, the right operand is ignored (because the result must be false). For ||, if the left operand is true, the right operand is ignored. This is useful for guarding against nil pointers or avoiding expensive calculations.

Code Breakdown

9-10
Declaring booleans. 'isActive' is initialized to the zero value (false). 'isValid' uses type inference to become a bool.
29
Demonstrating short-circuit OR. Since the first part is 'true', the entire expression is guaranteed to be true. Go skips calling 'expensiveCheck()', saving resources.
34
Demonstrating short-circuit AND. Since the first part is 'false', the entire expression must be false. Again, 'expensiveCheck()' is skipped.